[LeetCode] Excel Sheet Column Number

linspiration發表於2018-01-15

Problem

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 

Solution

class Solution {
    public int titleToNumber(String s) {
        int n = s.length();
        int sum = 0, base = 1;
        for (int i = n-1; i >= 0; i--) {
            sum += (s.charAt(i) - `A` + 1) * base;
            base *= 26;
        }
        return sum;
    }
}

相關文章