LeetCode 171. Excel Sheet Column Number (Excel 表格列数字)

时间:2023-03-08 17:47:21

Related to question Excel Sheet Column Title

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

题目标签:Math

  这一题和 #168 是逆向思维。

  从string s 的最右边遍历,每次拿一个 char, 减去 ‘A’, 记得要加1才得到正确的值。

  剩下的就和10进制是一样的,还要乘以 1, (26^1, 26^2, ...)

Java Solution:

Runtime beats 52.26%

完成日期:06/14/2017

关键词:26进制

关键点:A 对应 1,所以要 + 1

 class Solution
{
public int titleToNumber(String s)
{
int res = 0;
int mul = 1; // iterate s from right to left
for(int i = s.length() - 1; i >= 0; i--)
{
res = (s.charAt(i) - 'A' + 1) * mul + res; // need to + 1 cause A - 1
mul *= 26; // need to multiply 26 for next round
} return res;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/