【LeetCode】#171 Excel Sheet Column Number(C#)

● 問題

Given a column title as appear in an Excel sheet, return its corresponding column number.

Example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28


● 思考點

先找出ASCII的基準點'A',接下來我們知道A-Z總共26個字母,表示26進位轉換。

Example1:
AB:26*1(A) + 2(B) = 28
BC:26*2(B) + 3(C) = 55
ABC:(26 * 1(A) = 26)  ([26 + 2(B)] * 26 = 728) (728 + 3(C) = 731)      
Example2:
AB:26*1(A) + 1*2(B) = 28
BC:26*2(B) + 1*3(C) = 55
ABC:676*1(A) + 26*2(B) + 1*3(C) = 731      


● Solution

(1)

public class Solution {
    public int TitleToNumber(string s) {
        
        int result = 0;
        
        for(int i = 0; i < s.Length; i++)
        {
            result = result * 26 + (s[i] - 'A' + 1);
        }
        
        return result;
    }
}

(2)

public class Solution {
    public int TitleToNumber(string s)
    {
        int result = 0;
        int exp = s.Length - 1;

        for (int i = 0; i < s.Length; i++)
        {
            double tmp = (s[i] - 'A' + 1);
            tmp = tmp * Math.Pow(26, exp--);
            result += Convert.ToInt32(tmp);
        }

        return result;
    }
}