171. Excel 表列序号
给你一个字符串 columnTitle
,表示 Excel 表格中的列名称。返回 该列名称对应的列序号 。
例如:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
…
示例 1:
输入: columnTitle = “A”
输出: 1
示例 2:
输入: columnTitle = “AB”
输出: 28
示例 3:
输入: columnTitle = “ZY”
输出: 701
提示:
1 <= columnTitle.length <= 7
columnTitle
仅由大写英文组成columnTitle
在范围["A", "FXSHRXW"]
内
记录题解
public class ExcelSheetColumnNumber{
public static void main(String[] args) {
Solution solution = new ExcelSheetColumnNumber().new Solution();
System.out.println(solution.titleToNumber("FXSHRXW"));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int titleToNumber(String columnTitle) {
char[] chars = columnTitle.toCharArray();
int len = chars.length;
int ans = 0;
for (int i = len-1; i >= 0; i--) {
int temp = (int) (((chars[i] - 'A')+1)*Math.pow(26,len-i-1));
ans += temp;
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
力扣官方题解
class Solution {
public int titleToNumber(String columnTitle) {
int number = 0;
int multiple = 1;
for (int i = columnTitle.length() - 1; i >= 0; i--) {
int k = columnTitle.charAt(i) - 'A' + 1;
number += k * multiple;
multiple *= 26;
}
return number;
}
}