Day 15 - LeetCode 171. Excel Sheet Column Number

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 

翻譯

將Excel欄位轉換成數字。

想法

英文字母有26位, 代表26進位, 每進一位就要開更號, A的ANSI CODE = 65, 所以要-64 才會是 1
ex: AC = (65 - 64) * (26 更號 1) + (67 - 64) * (26 更號 0) = 29;
A: (65 - 64) * (26 更號 1)
C: (67 - 64) * (26 更號 0)

ex: BCD = (66 - 64) * (26 更號 2) + (67 - 64) * (26 更號 1) + (68 - 64) * (26 更號 0 ) = 1352 + 78 + 4 = 1434 ;

更號:自己*自己, 更號0等於1

ANSI CODE : http://www.alanwood.net/demos/ansi.html

詳細參閱

https://skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/171md.html

https://discuss.leetcode.com/topic/70593/js-one-line-solutioin


Code

/**
 * @param {string} s
 * @return {number}
 */
var titleToNumber = function(s) {
    let sum = 0;
    let i = 0;
    let len = s.length - 1;

    while (len >= 0) {
        //A的ANIS CODE = 65, 從最後一位數開始
        value = s.charCodeAt(len) - 64;
        // 英文字母有26位,0 次方= 1
        value = value * Math.pow( 26, i++);
        sum += value;
        len--;
    }
    return sum;
}
/**
 * @param {string} s
 * @return {number}
 */
var titleToNumber = function(s) {
    let letter_count = 26;
    let base_charcode = 'A'.charCodeAt(0) - 1;
    
    return s.split('').reduce( 
        (acc, cur) => 
            acc * letter_count + cur.charCodeAt(0) - base_charcode
            , 0);
};

Run

Your input
"AAAA"
"AAAB"
"A"
"AC"
"AZ"
"BA"
"QWEA"
"BCD"

Your answer
18279
18280
1
29
52
53
314471
1434

Expected answer
18279
18280
1
29
52
53
314471
1434

Runtime: 92 ms

留言