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





Solution:
经过分析不难发现实际上就是数对于 26 进制的转换用字母表示出来。
代码如下:
 1 class Solution:
 2     # @param {integer} n
 3     # @return {string}
 4     def convertToTitle(self, n):
 5         ans = ""
 6         while (n>0):
 7             temp = (n + 25) % 26 + 1
 8             ans = chr(temp + ord("A") - 1) + ans
 9             n = (n-1)/26
10         return ans

不过,还是需要注意的是,这个进制转换有效的是 1..26 而不是一般的 0..25。

所以在求当前位上的数字时,采取把 n 加上25后对26取余再加 1,这样就把所有的映射从 0..25 换到了 1..26。

同时,用 (n-1)/26,这样即便当前 n 是 26 的倍数,也不至于会 “进位” 。

相关文章:

  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-20
  • 2021-11-07
  • 2022-12-23
猜你喜欢
  • 2021-07-05
  • 2021-08-08
  • 2021-11-20
  • 2021-08-24
  • 2022-02-10
相关资源
相似解决方案