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代码如下:
1 public class Solution { 2 public int titleToNumber(String s) { 3 int n = s.length(); 4 int multi = 1; 5 int sum = 0; 6 for(int i = n-1;i>=0;i--){ 7 sum += (s.charAt(i)-'A'+1)*multi; 8 multi *= 26; 9 } 10 return sum; 11 } 12 }