171. Excel Sheet Column Number

The Title and 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 
...
Copy the code

Example 1:

Input: columnTitle = "A"
Output: 1
Copy the code

Example 2:

Input: columnTitle = "AB"
Output: 28
Copy the code

Example 3:

Input: columnTitle = "ZY"
Output: 701
Copy the code

Example 4:

Input: columnTitle = "FXSHRXW"
Output: 2147483647
Copy the code

 

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;

};
Copy the code

171. Excel table number

Topic Description:

You are given the string columnTitle, which represents the column name in an Excel table. Returns the column ordinal of the column name.

For example,

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

 

Example 1:

Input: columnTitle = "A" Output: 1Copy the code

Example 2:

Input: columnTitle = "AB" Output: 28Copy the code

Example 3:

Input: columnTitle = "ZY" Output: 701Copy the code

Example 4:

Input: columnTitle = "FXSHRXW" Output: 2147483647Copy the code

Tip:

  • 1 <= columnTitle.length <= 7
  • ColumnTitle Consists of only uppercase English
  • ColumnTitle is in the range [“A”, “FXSHRXW”]

Their thinking

  1. This is A variant of the base conversion. You can view it as the base 26 number represented by A~Z, but note that A corresponds to 1, not 0.
  2. Use the charCodeAt() method to return the Unicode encoding of the character at the specified position.
  3. The for loop iterates through the string from back to front, each carrying a weight of 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;

};
Copy the code