[leetcode-415-Add Strings]
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - 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; }
参考: