171. Excel Sheet Column Number

104 阅读1分钟

题目描述

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

Constraints:
1 <= s.length <= 7 s consists only of uppercase English letters.
s is between "A" and "FXSHRXW".

解题思路

与168题相反, 这个是26进制转十进制, 按照正常的方法来做就好

示例代码

func titleToNumber(_ s: String) -> Int {
    let cArr = Array(s)
    let A: Character = "A"
    var result = 0
    for idx in 0..<cArr.count {
        let c = cArr[idx]
        if let nI = c.asciiValue,
            let nA = A.asciiValue {
            let offset = nI - nA + 1
            result += (Int(offset) * Int(pow(26, Double(cArr.count - idx - 1))))
        }
    }
    return result
}