my swift solution, beats 100%


  • 0
    W
    class Solution {
        func addStrings(_ num1: String, _ num2: String) -> String {
        
        var arr1:[UnicodeScalar] = num1.unicodeScalars.reversed()
        var arr2:[UnicodeScalar] = num2.unicodeScalars.reversed()
        var carry = 0;
        var index = 0;
        var res = "";
        while index < arr1.count || index < arr2.count {
            var n1 = 0
            var n2 = 0
            if index < arr1.count {
                let ch1 = arr1[index];
                n1 = Int(ch1.value) - Int("0".unicodeScalars.first!.value)
            }
            if index < arr2.count {
                let ch2 = arr2[index];
                n2 = Int(ch2.value) - Int("0".unicodeScalars.first!.value)
            }
            let sum = n1 + n2 + carry;
            res = String( sum % 10) + res
            carry = sum / 10
            index += 1
        }
        if carry > 0 {
            res = String(carry) + res
        }
        
        return res
    }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.