为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode171. Excel表列序号 | Excel Sheet Column Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9715346.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

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

Example 1:

Input: "A"
Output: 1

Example 2:

Input: "AB"
Output: 28

Example 3:

Input: "ZY"
Output: 701

 1 class Solution {
 2     func titleToNumber(_ s: String) -> Int {
 3         //26进制转10进制
 4         var n:Int = s.count
 5         var res:Int = 0
 6         var temp:Int = 1
 7         // A:65 Z:90
 8         for m in (0..<n).reversed()
 9         {
10             var letter = s[s.index(s.startIndex,offsetBy:m)]
11             var num:Int = Int()
12             //使用for-in循环遍历转化成String的letter
13             for scalar in String(letter).unicodeScalars
14             {
15                 num = Int(scalar.value)
16             }
17             //num - 65 + 1
18             res += (num - 64) * temp
19             temp *= 26 
20         }
21         return res
22     }
23 }

24ms

 1 class Solution {
 2             func titleToNumber(_ s : String) -> Int {
 3 
 4     var i  = 0
 5             var result = 0
 6             
 7             for char in s.unicodeScalars{
 8 result+=(Int(char.value)-64)*self.canWinNim2(n: (s.count-1-i))
 9                 
10                 i+=1
11             }
12                return result
13         }
14     func canWinNim2( n: Int) -> Int{
15         var count = n
16         var  ret=1
17         while count>0 {
18             ret =  self.canWinNim1(ret)
19             count-=1
20         }
21        
22         return ret
23        
24     }
25     func canWinNim1(_ n: Int) -> Int{
26         return n*26
27     }
28 }

16ms

 1 class Solution {
 2     func titleToNumber(_ s: String) -> Int {
 3   
 4       var columnNumber = 0
 5       let offset = 64   
 6        
 7       for letter in s.utf8 { 
 8         columnNumber = columnNumber * 26 + Int(letter) - offset
 9       }   
10       
11       return columnNumber
12     } 
13 }

20ms

 1 class Solution {
 2     func titleToNumber(_ s: String) -> Int {
 3         
 4         var s = Array(s)
 5         var result = 0
 6         for c in s {
 7             let num = getNumber(c)
 8             result = result * 26 + num
 9         }
10         
11         return result
12     }
13     
14     func getNumber(_ c: Character) -> Int {
15         return Int(c.unicodeScalars.first!.value - "A".unicodeScalars.first!.value) + 1
16     }
17     
18 }

 

posted @ 2018-09-27 20:21  为敢技术  阅读(404)  评论(0编辑  收藏  举报