[Swift]LeetCode168. Excel表列名稱 | Excel Sheet Column Title

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-qfpybxph-md.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a positive integer, return its corresponding column title as appear in an Excel sheet.git

For example:github

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

Example 1:微信

Input: 1
Output: "A"

Example 2:app

Input: 28
Output: "AB"

Example 3:spa

Input: 701
Output: "ZY"

給定一個正整數,返回它在 Excel 表中相對應的列名稱。code

例如,htm

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

示例 1:blog

輸入: 1
輸出: "A"

示例 2:get

輸入: 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 }
相關文章
相關標籤/搜索