Skip to content

Latest commit

 

History

History
60 lines (52 loc) · 1.14 KB

File metadata and controls

60 lines (52 loc) · 1.14 KB
  1. 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 
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.

my thoughts:

1. convert integer to a 26-based number.

my solution:

**********26ms
class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = []
        a = "ZABCDEFGHIJKLMNOPQRSTUVWXYZ"
        while n/26>0 or n%26>0:
            res.append(a[n%26])
            n = n/26 if n%26 != 0 else n/26-1        
        res.reverse()
        return ''.join(res)

my comments:


from other ppl's solution:

use (n-1)/26 to get index 0 involved and avoid carrier issue
1. direct char manipulation, 22ms:
class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        ans = ""
        while n:
            ans = chr((n - 1) % 26 + ord('A')) + ans
            n = (n - 1) / 26
        return ans;