LeetCode 168. Excel表列名称 Excel Sh
2019-08-20 本文已影响0人
1江春水
【题目描述】
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
【示例1】
输入: 1
输出: "A"
【示例2】
输入: 28
输出: "AB"
【示例3】
输入: 701
输出: "ZY"
【思路】
1、其实就是求 10进制转26进制
2、注意:26进制没有26这个数字,就像2进制只有0 1没有2一个道理
3、时间复杂度O(log26n) 以26为底n的对数
4、空间复杂度O(1)
代码实现:
func convertToTitle(_ n: Int) -> String {
if n == 0 { return "" }
let arr = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var res = String()
var tmpN = n
while tmpN > 0 {
tmpN-=1//
res = arr[tmpN%26] + res
tmpN/=26
}
return res
}