跳转至

171. Excel Sheet Column Number

Leetcode Math

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

分析

相当于把26进制数转换为10进制数字。从最低位到最高位依次转换,某一位的系数用addOn表示。

public int titleToNumber(String s) {
    int res = 0;
    int n = s.length();
    int addOn = 1;
    for (int i = 0; i < n; i++) {
        res += addOn*(s.charAt(n - i - 1) - 'A' + 1);
        addOn = addOn*26;
    }
    return res;
}