Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

171. Excel 表列序号 #27

Open
zpc7 opened this issue Aug 7, 2022 · 0 comments
Open

171. Excel 表列序号 #27

zpc7 opened this issue Aug 7, 2022 · 0 comments
Labels
简单 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 7, 2022

171. Excel 表列序号

/**
 * @param {string} columnTitle
 * @return {number}
 */
// 方法1
var titleToNumber = function (columnTitle) {
    // 先制作A->1 Z->26的基础映射表
    const map = {}

    const baseCharCode = 65; // 字符A对应的ASCII码
    for (let i = 0; i < 26; i++) {
        const key = String.fromCharCode(baseCharCode + i);
        map[key] = i + 1
    }

    // 计算序号
    let res = 0;
    for (let i = 0; i < columnTitle.length; i++) {
        const cur = columnTitle[i];
        res += map[cur] * Math.pow(26, columnTitle.length - i - 1)
    }
    return res;
};
// 方法2
var titleToNumber = function(columnTitle) {
    let number = 0;
    let multiple = 1;

    for (let i = columnTitle.length - 1; i >= 0; i--) {
        // 跟字符A的差值
        const k = columnTitle[i].charCodeAt() - 'A'.charCodeAt() + 1;
        // 累加
        number += k * multiple;
        // 每次循环 乘数翻倍 相当于Math.pow
        multiple *= 26;
    }
    return number;
};
@zpc7 zpc7 added 简单 LeetCode 难度定级 JS and removed JS labels Aug 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant