Leetcode 171. Excel Sheet Column Number
在线提交: https://leetcode.com/problems/excel-sheet-column-number/
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进制字符串转为10进制数字,可看成是多项式展开, 不同位的权weigh是26的不同的幂次方。
已AC代码:
public class Solution
{
public int TitleToNumber(string s)
{
int len = s.Length;
int sum = 0;
int weigh = 1; // 该位的权, 26^0 ~ 26^(n-1)
for (int i = len; i >= 1; i--)
{
sum += (s[i - 1] - 'A' + 1) * weigh; // 从低位开始累加
weigh *= 26;
}
return sum;
}
}
Rank: You are here! Your runtime beats 99.39% of csharp submissions.