LeetCode – 43. Multiply Strings

題目連結: https://leetcode.com/problems/multiply-strings/

參考解法:

https://medium.com/@ChYuan/leetcode-43-multiply-strings-%E5%BF%83%E5%BE%97-medium-c33e8be94919

https://leetcode.com/problems/multiply-strings/discuss/562036/Swift-Explanation-Detailed-step-by-step

Note:

題目雖不允許字串換成數字,但仍可以把Character換成數字

func multiply(_ num1: String, _ num2: String) -> String {
    guard num1.count > 0 && num2.count > 0 else { return "" }
    let arr1 = Array(num1)
    let arr2 = Array(num2)
    var sum = Array(repeating: 0, count: num1.count + num2.count)
    for (i, a) in arr1.reversed().enumerated() {
        for (j, b) in arr2.reversed().enumerated() {
            let p1 = i + j
            let p2 = i + j + 1
            let val = (a.wholeNumberValue ?? 0) * (b.wholeNumberValue ?? 0) + sum[p1]
            sum[p1] = val % 10
            sum[p2] += val / 10
        }
    }
    sum.reverse()
    while sum.count > 1 && sum[0] == 0 {
        sum.removeFirst()
    }
    return sum.map{ String($0) }.joined()
}