【leetcode刷题笔记】Excel Sheet Column Number

时间:2024-12-16 21:35:39

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

题解:其实就是一个26进制数转换成十进制数的程序:s[0]*26^(n-1)+s[1]*26^(n-2)+...+s[n-1]*26^(0)。计算的时候为了方便,从字符串最后一位开始计算,设置一个multi变量,初始值为1,每次多累加一位,就增加26倍。

Java代码如下:

 public class Solution {
public int titleToNumber(String s) {
int n = s.length();
int multi = 1;
int sum = 0;
for(int i = n-1;i>=0;i--){
sum += (s.charAt(i)-'A'+1)*multi;
multi *= 26;
}
return sum;
}
}