题目描述:
用字符串模拟两个大数相加。
public static String bigNumberAdd(String str1, String str2) {
//翻转
char[] arr1 = new StringBuilder(str1).reverse().toString().toCharArray();
char[] arr2 = new StringBuilder(str2).reverse().toString().toCharArray();
int len1 = arr1.length;
int len2 = arr2.length;
int len = len1 > len2 ? len1 : len2;
int[] result = new int[len + 1];
for(int i = 0; i < len + 1; i++) {
int num1 = i < len1 ? (arr1[i] - '0') : 0;
int num2 = i < len2 ? (arr2[i] - '0') : 0;
result[i] = num1 + num2;
}
//处理进位
for(int i = 0; i < result.length; i++) {
if(result[i] >= 10) {
result[i+1] = result[i+1] + result[i] / 10;
result[i] = result[i] % 10;
}
}
StringBuilder sb = new StringBuilder();
boolean flag = true;
for(int i = len; i >= 0; i--) {
if(result[i] == 0 && flag) {
continue;
} else {
flag = false;
}
sb.append(result[i]);
}
return sb.toString();
}
网友评论