Swift, C++ for easy understand


  • 0
    X

    add both strings from end to the head, use carry to remember the last carry number;

    // Swift
    class Solution {
        // convert Char to UnicodeScalar from String is toooo hard for me, so let's use an easier way:
        private let charToInt : [Character : Int] = [
            "0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4,
            "5" : 5, "6" : 6, "7" : 7, "8" : 8, "9" : 9
        ]
        
        func addStrings(_ num1: String, _ num2: String) -> String {
            let chars1 = Array(num1.characters)
            let chars2 = Array(num2.characters)
            var i = chars1.count - 1
            var j = chars2.count - 1
            var carry : Int = 0, sum : Int = 0
            var rlt: String = ""
    
            while i >= 0 || j >= 0 {
                let n1 = i >= 0 ? charToInt[chars1[i]] : 0
                let n2 = j >= 0 ? charToInt[chars2[j]] : 0
                sum = n1! + n2! + carry
                carry = sum / 10
                rlt = "\(sum % 10)" + rlt
                i -= 1
                j -= 1
            }
            if carry > 0 { // check the last carry for entire string;
                rlt = "\(carry)" + rlt
            }
            return rlt
        }
    }
    
    
    //C++
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            int carry = 0, sum = 0;
            string rlt = "";
            int i = num1.size() - 1, j = num2.size() - 1;
            int n1, n2;
            while(i >= 0 || j >= 0){
                n1 = (i >= 0) ? num1[i] - '0' : 0; 
                n2 = (j >= 0) ? num2[j] - '0' : 0; 
                sum = n1 + n2 + carry;
                carry = sum / 10;
                rlt = to_string(sum % 10) + rlt; 
                i--; j--; 
            }
            if(carry > 0){
                rlt = to_string(carry) + rlt;
            }
            return rlt;
        }
    };
    

Log in to reply
 

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