Given a string columnTitle that represents the 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
…
Example 1:
Input: columnTitle = “A”
Output: 1
Example 2:
Input: columnTitle = “AB”
Output: 28
Example 3:
Input: columnTitle = “ZY”
Output: 701
把Excel表格中的列数转为对应的数字。A~Z分别表示1~26。
思路:
归根到底是26进制数字的问题。
就像十进制数个位乘100,十位乘101,百位乘102一样,
26进制数最低位的数字乘以260,往高位走依次乘以261, 262…
那A~Z怎么对应1~26呢,只需要将 字符-‘A’+1即可,如’A’,‘A’ - ‘A’ + 1 = 1
public int titleToNumber(String columnTitle) {
int result = 0;
int n = columnTitle.length();
int index = 0;
for(int i = n-1; i >= 0; i--) {
result += (columnTitle.charAt(i) - 'A' + 1) * Math.pow(26, index);
index ++;
}
return result;
}