168. Excel Sheet Column Title

https://leetcode.com/problems/excel-sheet-column-title/#/description

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 

Sol:

For input number, we take the remainder of it divided by 26, then use the remainder from 0 to 25 to append a corresponding capital letter to an empty list. Then update the number to number// 26 to find the next capital letter. 

Finally, we output the list in a reverse manner.  

class Solution(object):
    def convertToTitle(self, num):
        """
        :type n: int
        :rtype: str
        """
        # return a string
        # ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4. 
        # But how to get the column title from the number? We can't simply use the n%26 method because: ZZZZ=Z×26³+Z×26²+Z×26¹+Z=26×26³+26×26²+26×26¹+26
        # We can use (n-1)%26 instead, then we get a number range from 0 to 25.
        capitals = [chr(x) for x in range(ord('A'), ord('Z') + 1)]  
        result = []
        while num > 0:
            result.append(capitals[(num - 1)%26])
            num = (num-1) // 26
        result.reverse()
        return ''.join(result)

Note:

1 The reseason why we use (num - 1) % 26 rather than num % 26 to encode is that:

(num - 1) % 26 

for i in range(1, 26+1):
    print i % 26

==>

1

2

3

...

25

0

It is not convienent to use them as the indice as the array[ABCDEF...Z]

However, 
num % 26


for j in range(0, 25+1):
print j %26

==>

0

1

2

...

25

原文地址:https://www.cnblogs.com/prmlab/p/6970749.html