设计一个加法,满足100位的数字相加?
代码
public static String bigNumSum(String bigNumA, String bigNumB) {
// 1.String 转为char 数组
char[] bigNumAChars = new StringBuilder(bigNumA).reverse().toString().toCharArray();
char[] bigNumBChars = new StringBuilder(bigNumB).reverse().toString().toCharArray();
// 2.长数组加1 来存结果
int resultLength = bigNumAChars.length > bigNumBChars.length ? bigNumAChars.length : bigNumBChars.length;
int[] result = new int[resultLength + 1];
// 3.对位相加
for (int i = 0; i < resultLength; i++) {
// 如果当前的i超过了某个数组的长度,就用0代替高位了,和另一个字符数组中的数字相加
int Aint = i < bigNumAChars.length ? (bigNumAChars[i] - '0') : 0;
int Bint = i < bigNumBChars.length ? (bigNumBChars[i] - '0') : 0;
int temp = result[i];
temp += Aint;
temp += Bint;
result[i] = temp;
// 判断是否进位
if (temp >= 10) {
result[i + 1] = temp / 10;
result[i] = temp % 10;
}
}
// 4. 存储最后的结果
StringBuilder sb = new StringBuilder();
// 判断最高位是0还是1, 0无需保存
if (result[result.length - 1] == 1) {
sb.append(1);
}
for (int i = result.length - 2; i >= 0; i--) {
sb.append(result[i]);
}
return sb.toString();
}