[LeetCode] 168. Excel Sheet Column Title_Easy tag: Math

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 
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

这个题目实际上就想用26进制去将integer转换为string而已.可以看到如果是n%26, 如果是0, 那么就是Z, 否则的话就是chars[n%6], 并且之前的n/26要减一.

Code

1) 基本做法

class Solution:
    def convertToTitle(self, n):
        chars, rem, ans = 'Z' + string.ascii_uppercase, 1, ""
        while n > 0:
            rem, n = divmod(n, 26)
            ans += chars[n]
            if n == 0:
                rem -= 1
            n = rem
        return ans[::-1]

2) 利用chr(ord('A') + n) 去代替chars

class Solution:
    def converToTitle(self, n):
        ans = ""
        while n > 0:
            rem, n = divmod(n-1, 26)
            ans += chr(ord('A') + n)
            n = rem
        return ans[::-1]

3) 利用2) 的算法, 但是我们用recursive方式

class Solution:
    def converToTitle(self, n):
        return "" if n == 0 else self.converToTitle((n-1)/26) + chr(ord('A') + (n-1)%26)

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9491761.html