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

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

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

For example:github

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

Example 1:微信

Input: "A"
Output: 1

Example 2:app

Input: "AB"
Output: 28

Example 3:spa

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 }

24msscala

 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 }

16mscode

 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 }

20mshtm

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