C#版[击败99.39%的提交] - Leetcode 171. Excel表列序号 - 题解

Leetcode 171. Excel表列序号 - 题解

Leetcode 171. Excel Sheet Column Number

在线提交:
https://leetcode.com/problems/excel-sheet-column-number/

Description


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

  • Difficulty: Easy

  • Total Accepted:174.7K

  • Total Submissions:355.7K

  • Contributor:ts

  • Subscribe to see which companies asked this question.

    Related Topics Math
    Similar Questions Excel Sheet Column Title


思路:

这个问题实际上是要求将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.

猜你喜欢

转载自blog.csdn.net/yanglr2010/article/details/80878129