在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 }
|
请发表评论