原题网址:https://leetcode.com/problems/add-strings/
Given two non-negative numbers 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.
方法:自己实现加法。
public class Solution {
public String addStrings(String num1, String num2) {
char[] na1 = num1.toCharArray();
char[] na2 = num2.toCharArray();
char[] sa = new char[Math.max(na1.length, na2.length)];
int carry = 0;
for(int i = na1.length - 1, j = na2.length - 1, k = sa.length - 1; i >= 0 || j >= 0; i--, j--, k--) {
int s = 0;
if (i >= 0 && j >= 0) {
s = na1[i] - '0' + na2[j] - '0' + carry;
} else if (i >= 0) {
s = na1[i] - '0' + carry;
} else {
s = na2[j] - '0' + carry;
}
sa[k] = (char)('0' + (s % 10));
carry = s / 10;
}
if (carry == 0) {
return new String(sa);
}
return carry + new String(sa);
}
}