Skip to content

Latest commit

 

History

History
63 lines (53 loc) · 2.22 KB

0168._excel_sheet_column_title.md

File metadata and controls

63 lines (53 loc) · 2.22 KB

Navigation

Links:

  1. https://leetcode.com/problems/excel-sheet-column-title/
  2. https://leetcode-cn.com/problems/excel-sheet-column-title/

Solution 1 本质上是10进制转换26进制

A   1     AA    26+ 1     BA  2×26+ 1     ...     ZA  26×26+ 1     AAA  1×26²+1×26+ 1
B   2     AB    26+ 2     BB  2×26+ 2     ...     ZB  26×26+ 2     AAB  1×26²+1×26+ 2
.   .     ..    .....     ..  .......     ...     ..  ........     ...  .............   
.   .     ..    .....     ..  .......     ...     ..  ........     ...  .............
.   .     ..    .....     ..  .......     ...     ..  ........     ...  .............
Z  26     AZ    26+26     BZ  2×26+26     ...     ZZ  26×26+26     AAZ  1×26²+1×26+26

class Solution:
    def convertToTitle(self, n):
        res = ''
        distance = ord('A')

        while n:
            n -= 1
            n, remainder = divmod(n, 26)
            res = chr(remainder + distance) + res
        
        return res

class Solution:
    def convertToTitle(self, n):
        res = ''
        distance = ord('A')

        while n:
            n -= 1
            remainder = n % 26
            n = n // 26
            res = chr(remainder + distance) + res
        
        return res

Solution 2 递归写法

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

为什么减一?

26进制的范围为0~25,而本题是1~26。 第一种说法:'A' + 'n % 26',要进行这个操作之前,'A'已经代表1,所以后面的n要先减去一。 第二种说法:changing from 1-based to 0-based system。changing from 1-based index to 0-based index。就是把从1开始的index改为从0开始的index。从0开始才能进行10进制转换为其他进制的转换操作(divmod)。