2015.1.23 17:54
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:
This is a reversed version of the paired question. So do it backward.
Accepted code:
1 // 1AC, nice and easy 2 class Solution { 3 public: 4 int titleToNumber(string s) { 5 int base = 1; 6 int i; 7 int len = s.length(); 8 int sum = 0; 9 10 for (i = 0; i < len; ++i) { 11 sum = sum * 26 + (s[i] - 'A'); 12 } 13 for (i = 1; i < len; ++i) { 14 base *= 26; 15 sum += base; 16 } 17 sum += 1; 18 19 return sum; 20 } 21 };