[LeetCode]:171:Excel Sheet Column Number
题目:
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进制转10进制,从低到高按位计算
代码:
public class Solution { public static int titleToNumber(String s) { int intResult = 0; char[]chars=s.toCharArray(); int n =0; for(int i = chars.length; i>0;i--){ intResult = intResult + ((int)chars[i-1]-64)*caleOffset(n); n++; } return intResult; } public static int caleOffset(int n) { int intResult = 1; for(int i = 0; i< n;i++){ intResult = intResult*26; } return intResult; } }
高手的代码:从高位到低位,进位乘以26
class Solution { public: int titleToNumber(string s) { int ret = 0; for(int i = 0; i < s.size(); i ++) ret = ret*26 + (s[i]-'A'+1); return ret; } };