C++ O(n) Solution


  • 0
    Q

    class Solution {
    public:
    string addStrings(string num1, string num2) {
    vector<int> n1;
    vector<int> n2;
    int len1 = num1.size();
    int len2 = num2.size();
    int c = 0;
    string result ="";
    char tmp;
    for(int i = 0;i < len1;i++){
    n1.push_back(num1[len1-i-1]-'0');
    }
    for(int i = 0;i < len2;i++){
    n2.push_back(num2[len2-i-1]-'0');
    }
    if(len1 > len2){
    for(int i = len2;i < len1;i++){
    n2.push_back(0);
    }
    for(int i = 0;i < len1;i++){
    if(n2[i] + n1[i] + c < 10){
    tmp = n2[i] + n1[i] + c +'0';
    result = tmp + result;
    c = 0;
    }
    else{
    tmp = n2[i] + n1[i] + c -10 +'0';
    result = tmp + result;
    c = 1;
    }
    }
    }else{
    for(int i = len1;i < len2;i++){
    n1.push_back(0);
    }
    for(int i = 0;i < len2;i++){
    if(n2[i] + n1[i] + c < 10){
    tmp = n2[i] + n1[i] + c +'0';
    result = tmp + result;
    c = 0;
    }
    else{
    tmp = n2[i] + n1[i] + c -10 +'0';
    result = tmp + result;
    c = 1;
    }
    }
    }
    if(c == 1){
    tmp = 1 + '0';
    result = tmp + result;
    }
    return result;
    }
    };


Log in to reply
 

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