[Algorithm] 171. Excel Sheet Column Number

 

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

 

Basiclly, it is 26-based, the same as 10-based, 

102 = 1 +                                       1

previous result * 10 + 0   +             1*10+0=10

previous result * 10 +2   +              10*10+2=102

 

AAA = 

1 +

1 * 26 +1

27 * 26 + 1 = 703

/**
 * @param {string} s
 * @return {number}
 */
var titleToNumber = function(s) {
    
    if (!s) {
        return 0;
    }
    
    let sum = 0;
    let len = s.length;
    for (let i = 0; i < len; i++) {
        sum = sum * 26 + (s[i].charCodeAt() - 64);
    }
      
    return sum;
};

 

上一篇:03.14 ICPC训练联盟周赛,Preliminaries for Benelux Algorithm Programming Contest 2019


下一篇:Montgomery