Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
public class Solution {
public int titleToNumber(String s) {
int tmp = 1;
int j = 0;
int len = s.length();
int res = s.charAt(len - 1 ) - 'A' + 1;
for(int i = len -2; i >= 0 ; i--){
char c = s.charAt(i);
j = len - i - 1;
while(j > 0){
tmp = tmp * 26;
j--;
}
res = res + tmp * (s.charAt(i) - 'A' + 1);
tmp = 1;
}
return res;
}
}
不算难,依次遍历即可。