当前位置:网站首页>168. excel table column name

168. excel table column name

2022-07-01 03:43:00 Sun_ Sky_ Sea

168. Excel Table column name

Original title link :https://leetcode.cn/problems/excel-sheet-column-title/

Give you an integer columnNumber , Back to it in Excel The name of the corresponding column in the table .

for example :

A -> 1
B -> 2
C -> 3

Z -> 26
AA -> 27
AB -> 28

Example 1:

Input :columnNumber = 1
Output :“A”
Example 2:

Input :columnNumber = 28
Output :“AB”
Example 3:

Input :columnNumber = 701
Output :“ZY”
Example 4:

Input :columnNumber = 2147483647
Output :“FXSHRXW”

Their thinking :

Calculate the corresponding letter from low to high by calculating the remainder and quotient , here 26 The radix calculation is 0 To 25 This 26 Number , but A It's from 1 At the beginning , So when calculating the remainder and quotient , In order to be able to communicate with 26 The base number remains the same , So subtract it first 1, Calculate again .

Code implementation :

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
      ans = []
      while columnNumber > 0:
          #  the reason being that 26 Base number :0~25, but A It's from 1 At the beginning , So the letters are relative to the normal 26 Decimal digit 
          #  Added one more 1, So it's using 26 In hexadecimal calculation , First subtract 1 individual 1
          columnNumber -= 1
          #  Calculate the remainder , The rightmost letter 
          cur = columnNumber % 26
          #  Convert letters 
          cur_ans = chr(cur + ord('A'))
          ans.insert(0, cur_ans)

          #  Seeking quotient , Calculate the next letter 
          columnNumber //= 26

      return ''.join(ans)

reference :
https://leetcode.cn/problems/excel-sheet-column-title/solution/excelbiao-lie-ming-cheng-by-leetcode-sol-hgj4/

原网站

版权声明
本文为[Sun_ Sky_ Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010323232494.html