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
我的解法:
从第一次的一堆到现在的5行,进步是看得见的,虽然缓慢,但是还是有进步的,加油!
从右向左,基本按照十进制的计算方法计算
中间有一部分是double向int转换,因为Math.pow计算出来是double的数
public class Solution {
public int titleToNumber(String s) {
int sum = 0;
int mul = 0;
for(int i = s.length() - 1; i >= 0; i--){
sum = sum + (s.charAt(i) - 'A' +1) * (int)Math.pow(26, mul);
mul++;
//Math.pow(double m, double n) 是求m的n次方
}
return sum;
}
}
从左向右计算,每次把上一次的数*26,妙啊!
public class Solution {
public int titleToNumber(String s) {
int result = 0;
for (int i = 0; i < s.length(); i++){
result *= 26;
result += ((s.charAt(i) - 'A') + 1);
}
return result;
}
}