leetcode每日一题题解——171. Excel 表列序号 (2021年7月30日)

492 阅读1分钟

171. Excel Sheet Column Number

Title Description:

Given a string columnTitle that represents the 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: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

Example 4:

Input: columnTitle = "FXSHRXW"
Output: 2147483647

 

Constraints:

  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

Problem solving ideas

  1. This topic is the deformation of base conversion, which can be regarded as 26 base numbers represented by A ~ Z, but it should be noted that a corresponds to 1 rather than 0.

  2. Use the charcodeat() method to return the Unicode encoding of the character at the specified position.

  3. The for loop traverses the string from back to front, and the weight of each bit is 26 ^ n.

code

/**
 * @param {string} columnTitle
 * @return {number}
 */
var titleToNumber = function (columnTitle) {
    let num = 0;
    let zimu = 1;

    for (var i = columnTitle.length - 1; i >= 0; i--) {
        let n = columnTitle[i].charCodeAt() - "A".charCodeAt() + 1;
        num += n * zimu;
        zimu *= 26;
        
    }
    return num;

};

171. Excel 表列序号

题目描述:

给你一个字符串 columnTitle ,表示 Excel 表格中的列名称。返回该列名称对应的列序号。

  例如,

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

 

示例 1:

输入: columnTitle = "A"
输出: 1

示例 2:

输入: columnTitle = "AB"
输出: 28

示例 3:

输入: columnTitle = "ZY"
输出: 701

示例 4:

输入: columnTitle = "FXSHRXW"
输出: 2147483647

提示:

  • 1 <= columnTitle.length <= 7
  • columnTitle 仅由大写英文组成
  • columnTitle 在范围 ["A", "FXSHRXW"] 内

解题思路

  1. 这道题目是进制转换的变形,可以看成是A~Z表示的26进制数,但是要注意的是A对应的是1而不是0。
  2. 用charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。
  3. for循环从后往前遍历字符串,每进一位权重为26^n。

代码

/**
 * @param {string} columnTitle
 * @return {number}
 */
var titleToNumber = function (columnTitle) {
    let num = 0;
    let zimu = 1;

    for (var i = columnTitle.length - 1; i >= 0; i--) {
        let n = columnTitle[i].charCodeAt() - "A".charCodeAt() + 1;
        num += n * zimu;
        zimu *= 26;
        
    }
    return num;

};