0171. Excel Sheet Column Number (E)
Excel Sheet Column Number (E)
题目
Given a 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: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
题意
将给定字母字符串转换为对应的整数。
思路
26进制转换。
代码实现
Java
class Solution {
public int titleToNumber(String s) {
int ans = 0;
for (int i = 0; i < s.length(); i++) {
int x = s.charAt(i) - 'A' + 1;
ans = ans * 26 + x;
}
return ans;
}
}
JavaScript
/**
* @param {string} s
* @return {number}
*/
var titleToNumber = function (s) {
let sum = 0
for (let c of s.split('')) {
sum = sum * 26 + c.charCodeAt() - 65 + 1
}
return sum
}