171. Excel Sheet Column Number--LeetCode Record

Tong_hdj發表於2016-07-11

Related to question Excel Sheet Column Title

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 
class Solution {
    func titleToNumber(s: String) -> Int {
        var sum:Int = 0
        var basic:Int = 1
        for (index, ch) in String(s).unicodeScalars.enumerate().reverse() {

            let chInt = Int(ch.value) - 64
            sum += basic * chInt
            basic *= 26
        }
        return sum
    }
}

TestCase

"A"
"AB"
"BA"
"ABC"
"CAB"

相關文章