Swift算法:Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:

  • The numbers can be arbitrarily large and are non-negative.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.
class Solution {
    func multiply(num1: String, _ num2: String) -> String {
        if num1 == "" || num2 == "" {
            return ""
        }
        
        var n1 = num1.characters.map { (c) -> Int in
            return Int("\(c)")!
        }
        var n2 = num2.characters.map { (c) -> Int in
            return Int("\(c)")!
        }
        n1 = n1.reverse()
        n2 = n2.reverse()
        
        var n3:[Int] = []
        for i in 0 ..< n2.count {
            let fix = Array(count: i, repeatedValue: 0)
            n3 = addTwoNumber(n3, a2: fix + mutiplySimply(n1, num2: n2[i]))
        }
        
        var result: String = n3.reverse().reduce("") { (s, num) -> String in
            return s + "\(num)"
        }
        
        while result.hasPrefix("0") {
            result.removeAtIndex(result.startIndex)
        }
        if result == "" {
            result = "0"
        }
        
        return result
    }
    
    //倒序输入 倒序输出
    func addTwoNumber(a1: [Int], a2: [Int]) -> [Int] {
        let c1 = a1.count
        let c2 = a2.count
        let c3 = c1= 10 {
                a3[i] = a3[i]%10
                carry = 1
            } else {
                carry = 0
            }
        }
        
        if c1 < c2 {
            for i in c1 ..< c2 {
                a3.append(a2[i]+carry)
                if a3[i] >= 10 {
                    a3[i] = a3[i]%10
                    carry = 1
                } else {
                    carry = 0
                }
            }
        } else if c1 > c2 {
            for i in c2 ..< c1 {
                a3.append(a1[i]+carry)
                if a3[i] >= 10 {
                    a3[i] = a3[i]%10
                    carry = 1
                } else {
                    carry = 0
                }
            }
        }
        
        if carry == 1 {
            a3.append(carry)
        }
        return a3
    }
    
    func mutiplySimply(num1: [Int], num2: Int) -> [Int] {
        let c1 = num1.count
        var num3: [Int] = []
        
        var carry = 0
        for i in 0 ..< c1 {
            num3.append(num1[i]*num2+carry)
            if num3[i] >= 10 {
                carry = num3[i]/10
                num3[i] = num3[i]%10
            } else {
                carry = 0
            }
        }
        
        if carry != 0 {
            num3.append(carry)
        }
        return num3
    }
}

你可能感兴趣的:(Swift算法:Multiply Strings)