https://leetcode.com/problems/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.
代码:
class Solution { public: string addStrings(string num1, string num2) { string c = ""; int len1 = num1.length(); int len2 = num2.length(); int len = max(len1, len2); for(int i = len1; i < len; i ++) num1 = "0" + num1; for(int i = len2; i < len; i ++) num2 = "0" + num2; int ok = 0; for(int i = len - 1; i >= 0; i --) { char temp = num1[i] + num2[i] - '0' + ok; if(temp > '9') { ok = 1; temp -= 10; } else ok = 0; c = temp + c; } if(ok) c = "1" + c; return c; } };
大数加法