1. Demand
- Given a column name in an Excel table, return its corresponding column number.
E.g,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: "A" Output: 1Example 2:
Input: "AB" Output: 28Example 3:
Input: "ZY" Output: 701
Two, base conversion
2.1 Thinking analysis
- A~Z represents 1~26, traverse the string, get the current character must be one of A~Z, convert the current character into the corresponding integer, these integers are expressed in the base 26, which can be converted into base 10 ;
2.2 Code implementation
class Solution {
public int titleToNumber(String s) {
int sum = 0;
for(int i = 0; i < s.length(); i++) {
int tmp = s.charAt(i) - 64;
sum = sum * 26 + tmp;
}
return sum;
}
}
2.3 Complexity analysis
- The time complexity is O(N), and traversing the string consumes O(N) extra space;
- The space complexity is O(1);