【BASE】Big Number by Swift

发布于: 2019-03-02 16:04
阅读: 13
评论: 0
喜欢: 0

问题

大数和大数加法运算。

分析过程

  • 输入:大数数据结构和加法运算。
  • 输出:无
  • 思路:见注释

解决方法

// A big number struct. Use [UInt8]
struct BigNumber {
    
    // Only '0' ~ '9'
    var data: Array<UInt8>
    
    init(count: Int = 1) {
        data = Array<UInt8>.init(repeating: 0, count: count)
    }
    
    init(number: UInt) {
        data = Array<UInt8>.init(repeating: 0, count: "\(number)".count)
        var i = 0;
        for char in "\(number)" {
            guard let num = Int("\(char)") else {
                break
            }
            data[i] = UInt8(num)
            i += 1
        }
    }
    
    func printSelf() {
        let str = data.reduce(into: "") { $0 = "\($0)\($1)" }
        print(str)
    }
}

// Big number plus
func +(a: BigNumber, b: BigNumber) -> BigNumber {
    var a = a
    var b = b
    a.data.reverse()
    b.data.reverse()
    
    let countA = a.data.count
    let countB = b.data.count
    
    let countMax = max(countA, countB)
    let countMin = min(countA, countB)
    let biggerNumber = countA > countB ? a : b
    
    var result = BigNumber.init(count: countMax)
    var carryFlag = false
    
    for i in 0..<countMin {
        var sum = a.data[i] + b.data[i]
        sum += carryFlag ? 1 : 0
        if sum >= 10 {
            sum = sum % 10
            carryFlag = true
        } else {
            carryFlag = false
        }
        result.data[i] = sum
    }
    
    for i in countMin..<countMax {
        var sum = biggerNumber.data[i]
        sum += carryFlag ? 1 : 0
        if sum >= 10 {
            sum = sum % 10
            carryFlag = true
        } else {
            carryFlag = false
        }
        result.data[i] = sum
    }
    
    if carryFlag {
        result.data.append(1)
    }
    result.data.reverse()
    
    return result
}

Thanks for reading.

All the best wishes for you! 💕