2017年4月28日 星期五

[LeetCode] 171. Excel Sheet Column Number

轉自LeetCode

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 
<Solution>
Excel Sheet Column Title 的相關題,只是變成從文字轉成數字

一樣也是一位一位處理,每增加一位是乘以26

code如下

class Solution {
public:
int titleToNumber(string s) {
int ans = 0;
for(const auto &c : s) {
ans *= 26;
ans += static_cast<int>(c - 'A' + 1);
}
return ans;
}
};

沒有留言:

張貼留言