[LeetCode] 171. Excel Sheet Column Number

Problem

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

For example:

1
2
3
4
5
6
7
8
    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28
    ...

Example 1:

1
2
Input: "A"
Output: 1

Example 2:

1
2
Input: "AB"
Output: 28

Example 3:

1
2
Input: "ZY"
Output: 701

Explanation

  1. This is a problem that asks us to convert a twenty-six hex to a decimal number.

  2. We can start from the most right, ‘A’ is 1, so we can do ‘A’ - ‘A’ + 1 = 1, then multiple by 26 to the power of 0; ‘B’ is 2, we can do ‘B’ - ‘A’ + 1 = 2, multiple by 26 to the power of 0. Similarlly, the second right number multiple by 26’s to the power of 1.

Solution

1
2
3
4
5
6
7
8
9
10
class Solution {
    public int titleToNumber(String s) {
        int len = s.length();
        int res = 0;
        for (int i = len-1; i >= 0; i--) {
            res += (s.charAt(i) - 'A' + 1) * Math.pow(26, len-1-i);
        }
        return res;
    }
}