天天看點

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.