[Swift]LeetCode168. Excel表列名称 | Excel Sheet Column Title
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9715135.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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 ...
Example 1:
Input: 1 Output: "A"
Example 2:
Input: 28 Output: "AB"
Example 3:
Input: 701 Output: "ZY"
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
示例 1:
输入: 1 输出: "A"
示例 2:
输入: 28 输出: "AB"
示例 3:
输入: 701 输出: "ZY"
1 class Solution { 2 func convertToTitle(_ n: Int) -> String { 3 var m:Int = n 4 var temp:String = String() 5 while(m > 0) 6 { 7 //A的ASCII为65 8 var num:Int = (m - 1) % 26 + 65 9 var s:Character = Character(UnicodeScalar(num)!) 10 temp = String(s) + temp 11 m = (m - 1)/26 12 } 13 return temp 14 } 15 }
8ms
1 class Solution { 2 func convertToTitle(_ n: Int) -> String { 3 4 guard n > 0 else { 5 return "" 6 } 7 var result = [Character]() 8 var n = n 9 while n > 0 { 10 n = n - 1 11 let a = n % 26 12 result.append(Character(UnicodeScalar(Int(65) + a )!)) 13 n /= 26 14 } 15 16 return String(result.reversed()) 17 18 } 19 }
12ms
1 class Solution { 2 func convertToTitle(_ n: Int) -> String { 3 var result = "" 4 var x = n 5 while x > 0 { 6 x -= 1 7 result = String(Character(UnicodeScalar(x % 26 + 65)!)) + result 8 x = x / 26 9 } 10 return result 11 } 12 }