Problem
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
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
Solution
/**
* @param {string} s
* @return {number}
*/
var titleToNumber = function(s) {
var res = 0;
var num = 0;
var len = s.length;
for (var i = 0; i < len; i++) {
num = getNum(s[len - 1 - i]);
res += Math.pow(26, i) * num;
}
return res;
};
var getNum = function (char) {
var start = 'A'.charCodeAt(0) - 1;
return char.charCodeAt(0) - start;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).