原题网址: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
num1andnum2is < 5100. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does 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);
}
}
本文介绍了一种不使用内置大数库或直接转换为整数的方法来实现两个大字符串表示的非负整数相加的问题。该方法适用于长度不超过5100的字符串,并确保输入字符串不含前导零。
274

被折叠的 条评论
为什么被折叠?



