LeetCode Notes: Excel Sheet Column Number
Question
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"]
.
For questions of the same type, please refer to
Solution
Analysis:
- Reverse the string and convert it to an array traversal
- Convert the character into a number from 1 to 26, and handle the carry according to the number of digits in the character
Code:
/**
* @param {string} columnTitle
* @return {number}
*/
var titleToNumber = function(columnTitle) {
let result = 0;
// Reverse the string and turn it into an array for traversal
columnTitle.split('').reverse().forEach((item,i)=>{
// The character is converted to UTF-16 code index value minus 64 to get the index value starting from 1, multiplying the i square of 26
// such as'BBA' => 2 * 26^2 + 2 * 26^1 + 1 * 26 ^0
result += (item.charCodeAt()-64) * Math.pow(26,i)
})
return result
};
Comments