Day 22 - LeetCode 168. Excel Sheet Column Title

LeetCode 168. Excel Sheet Column Title

題目

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 

翻譯

給一個正整數,回傳在excel表格中對應的欄位。

想法

'A'的charcode = 65, 英文字母總數是26個, 有點像26進位, 看起來可以跑迴圈用 String.fromCharCode(n % 26 + 64)處理, 但當字母為Z時 26 % 26 = 0, 變得無法取得正確字母
所以改用String.fromCharCode( (n - 1) % 26 + 'A'), 去取正確字母

詳細參閱

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


Code

/**
 * @param {number} n
 * @return {string}
 */
var convertToTitle = function(n) {
    //charcode(A) = 65; (Z) = 90;
    let base = 26;
    //charcode 轉數字差額
    let charcode_to_num_diff = 'A'.charCodeAt() - 1;
    //小於27, 可以直接顯示
    if ( n - 1 < base ) {
        return String.fromCharCode(n + charcode_to_num_diff);
    }

    let str = '';
    let excel_str = '';
    while ( n > 0 ) {
        if ( n % base == 0 ) {
            str = String.fromCharCode(n % base + charcode_to_num_diff + base);
            n = parseInt( (n - base) / base);
        } else {
            str = String.fromCharCode(n % base + charcode_to_num_diff);
            n = parseInt(n / base);
        }
        excel_str = str + excel_str;
        
    }

    return excel_str;
};
/**
 * @param {number} n
 * @return {string}
 */
var convertToTitle = function(n) {
    //英文字母總數
    let base = 26;
    //charcode(A) = 65; (Z) = 90;
    let charcode_to_num = 'A'.charCodeAt();
    //小於27(A~Z), 可以直接顯示
    if ( n - 1 < base ) {
        return String.fromCharCode( (n - 1) % base + charcode_to_num);
    }

    let str = '';
    let excel_str = '';

    while ( n > 0 ) {
        str = String.fromCharCode( (n - 1) % base + charcode_to_num);
        n = parseInt( (n - 1) / base);
        excel_str = str + excel_str;
    }

    return excel_str;
};

Run

留言