LeetCode – 171. Excel Sheet Column Number

題目連結: https://leetcode.com/problems/excel-sheet-column-number/

解法一:

func titleToNumber(_ columnTitle: String) -> Int {
    var result = 0
    for c in columnTitle {
        let value = (UnicodeScalar(String(c))?.value ?? 0) - UnicodeScalar("A").value + 1
        result = result * 26 + Int(value)
    }
    return result
}

解法二: (運用reduce)

func titleToNumber(_ columnTitle: String) -> Int {
    let arr = Array(columnTitle)
    return arr.reduce(0) { result, c in
        let value = (UnicodeScalar(String(c))?.value ?? 0) - UnicodeScalar("A").value + 1
        return result + Int(value)
    }
}