在线时间:8:00-16:00
迪恩网络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 }
|
请发表评论