前提
不使用BigDecimal类进行两大数计算, 不考虑负数情况与非整形计算 被加数比加数大
思路
将被加数与加数翻转,从各位开始计算,然后处理进位,然后在将结果倒序输出
public class BigDataCompute {
public static void main (String[] args) {
String a = "105" ;
String b = "6" ;
plus(a, b);
}
public static void plus (String a, String b) {
char [] numA = new StringBuilder(a).reverse().toString().toCharArray();
char [] numB = new StringBuilder(b).reverse().toString().toCharArray();
int [] result = new int [numA.length + 1 ];
for (int i = 0 ; i < result.length; i++) {
int intA = i < numA.length ? numA[i] - '0' : 0 ;
int intB = i < numB.length ? numB[i] - '0' : 0 ;
result[i] = intA + intB;
}
for (int i = 0 ; i < result.length; i++) {
if (result[i] >= 10 ) {
result[i + 1 ] += result[i] / 10 ;
result[i] = result[i] % 10 ;
}
}
System.out .println(Arrays.toString(result));
StringBuilder re = new StringBuilder();
boolean bool = true ;
for (int i = result.length - 1 ; i >= 0 ; i--) {
if (result[i] == 0 && bool ) {
continue ;
} else {
bool = false ;
}
re.append(result[i]);
}
System.out .println(re);
}
}