【leetcode】Excel Sheet Column Title & Excel Sheet Column Number

题目描述:

Excel Sheet Column Title

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

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 

Excel Sheet Column Number

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 

解题思路:

简单的数字和字符串的转换

Excel Sheet Column Title

class Solution:
    # @return a string
    def convertToTitle(self, num):
        alpha = [chr(i) for i in range(65,91)]
        res = []
        while num > 0:
            t = num % 26
            print t
            res.append(alpha[t-1])
            num = (num / 26)
            if t == 0:
                num -= 1
        return ''.join(res[::-1])

s = Solution()
print s.convertToTitle(52)

Excel Sheet Column Number

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        res = 0
        l = len(s)
        for i in range(l):
            res *= 26
            res += ord(s[i]) - 64
        return res

s = Solution()
print s.titleToNumber('Z')
posted @ 2014-12-30 00:38  mrbean  阅读(1424)  评论(0编辑  收藏  举报