题目描述

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

解法一

思路

这题实际上就是进制转换,即26进制转十进制,只是这里需要注意有1的偏移,即A -> 1以及Z -> 26

Python

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = 0
        for letter in s:
            result = result * 26 + ord(letter) - ord('A') + 1
        return result

Java

public class Solution {
    public int titleToNumber(String s) {
        int result = 0;
        for (char letter : s.toCharArray()) {
            result = result * 26 + letter - 'A' + 1;
        }
        return result;
    }
}

C++

class Solution {
public:
    int titleToNumber(string s) {
        int result = 0;
        for (auto letter : s) {
            result = result * 26 + letter - 'A' + 1;
        }
        return result;
    }
};