1, 题目

给定一个正整数,返回它在 Excel 表中相对应的列名称。

例如,

  1. 1 -> A
  2. 2 -> B
  3. 3 -> C
  4. ...
  5. 26 -> Z
  6. 27 -> AA
  7. 28 -> AB
  8. ...

示例 1:

  1. 输入: 1
  2. 输出: "A"

示例 2:

  1. 输入: 28
  2. 输出: "AB"

示例 3:

  1. 输入: 701
  2. 输出: "ZY"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/excel-sheet-column-title
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2, 算法

  1. object Solution {
  2. def convertToTitle(n: Int): String = {
  3. val base = 26
  4. val m = (1 to base).zip('A' to ('A' + base).toChar).toMap
  5. val stack = scala.collection.mutable.Stack[Char]()
  6. var x = n
  7. while (x != 0) {
  8. if (x % base != 0) {
  9. stack.push(m(x % base))
  10. x /= base
  11. } else {
  12. stack.push(m(base))
  13. x = x / base - 1
  14. }
  15. }
  16. stack.mkString("")
  17. }
  18. }
  1. class Solution:
  2. def convertToTitle(self, n: int) -> str:
  3. base = 26
  4. m = {}
  5. for x in range(1, base + 1):
  6. m.update({x: chr(x + 64)})
  7. result = []
  8. while n != 0:
  9. if n % base != 0:
  10. result.append(m[n % base])
  11. n //= base
  12. else:
  13. result.append(m[base])
  14. n = n // base - 1
  15. return ''.join(result[::-1])