码疯窝

LeetCode 每日一题 — Excel Sheet Column Number

2015/01/06 10:10:51    分类: 日志连载    0人评论 次浏览

Related to question Excel Sheet Column Title

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进制转换的了, 一样的原理.

参考链接: Excel Sheet Column Title

Java:

public class Solution {
    public int titleToNumber(String s) {
        int len = s.length();
        int rst = 0;
        int i = 0;
        for (i = 0; i < len; i++) {
            rst = rst * 26 + (int)s.charAt(i) - (int)'A' + 1;
        }
        return rst;
    }
}

C++:

class Solution {
public:
    int titleToNumber(string s) {
        int rst = 0;
        int i = 0;
        int len = s.length();
        for (i = 0; i < len; i++)
            rst = rst * 26 + s[i] - 'A' + 1;
        return rst;
    }
};

Python:

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        l = len(s)
        rst = 0
        for i in range(l):
            rst = rst * 26 + ord(s[i]) - ord('A') + 1
        return rst
继续查看有关 日志连载的文章

0个访客评论