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;
}
该博客介绍了如何将Excel表格中的列标题,例如'A'或'AB',转换成对应的数字。通过理解问题本质是一个26进制的计数系统,博主提供了算法实现,将每个字母减去'A'再加1,然后根据位置乘以26的相应幂次,最后累加得到结果。示例中展示了对于'A'、'AB'和'ZY'的转换过程。
460

被折叠的 条评论
为什么被折叠?



