[Leetcode] #415 Add Strings

来源:互联网 发布:灭蚊激光炮淘宝 编辑:程序博客网 时间:2024/06/05 18:31

Discription:

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.

Solution:

string addStrings(string num1, string num2) {if (num1.empty() || num2.empty())return num1.empty() ? num2 : num1;int m = num1.size() - 1, n = num2.size() - 1;string result = "";int carry = 0, temp;while (m >= 0 || n >= 0 || carry){temp = (m >= 0 ? num1[m--] - '0' : 0) + (n >= 0 ? num2[n--] - '0' : 0) + carry;result = char(temp % 10 + '0') + result;carry = temp / 10;}//if (carry > 0)//result = char(carry + '0') + result;return result;}
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;}

0 0