1. 程式人生 > >[leetcode-415-Add Strings]

[leetcode-415-Add Strings]

-a 手工 accept get scu ive digits num ||

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

思路:

模擬手工加法過程,用carry表示進位。

第一個是自己寫的,比較啰嗦。

第二個是參考的網上大神的,簡潔。

string addStrings(string num1, string num2)
     {
         int n1 = num1.length()-1, n2 = num2.length()-1;
         string ret="";
         int digit = 0;
         int carry = 0;
         int sum = 0;
         while (n1 >= 0 && n2 >= 0
) { sum = carry + num1[n1--] + num2[n2--] - 0 - 0; digit = sum %10; carry = (sum >= 10) ? 1 : 0; ret += (digit+0); } while (n1 >= 0) { sum = carry + num1[n1--] - 0; digit
= sum % 10; carry = (sum >= 10) ? 1 : 0; ret += (digit + 0); } while (n2 >= 0) { sum = carry + num2[n2--] - 0; digit = sum % 10; carry = (sum >= 10) ? 1 : 0; ret += (digit + 0); } if (carry) ret += 1; reverse(ret.begin(), ret.end()); return ret; }

string addStrings(string num1, string num2) {
    int i = num1.size() - 1;
    int j = num2.size() - 1;
    int carry = 0;
    string res = "";
    while(i>=0 || j>=0 || carry){
        long sum = 0;
        if(i >= 0){sum += (num1[i] - 0);i--;}
        if(j >= 0){sum += (num2[j] - 0);j--;}
        sum += carry; 
        carry = sum / 10;
        sum = sum % 10;
        res =  res + to_string(sum);
    }
    reverse(res.begin(), res.end());
    return res;
}

參考:

https://discuss.leetcode.com/topic/62305/c-_accepted_13ms

[leetcode-415-Add Strings]