描述
acmj最近发现在使用计算器计算高精度的大数加法时很不方便,于是他想着能不能写个程序把这个问题给解决了。
输入
每组数据包含两个正数A,B(可能为小数且位数不大于400)
输出
每组输出数据占一行,输出A+B的结果,结果需要是最简的形式。
样例输入
1.9 0.1
样例输出
2
代码如下:
import java.util.Scanner;
/** * Created by lcc on 2017/6/5. */
public class ABProblemIV {
public static void main(String[] args) {
Scanner input = new Scanner(system.in);
String str1 = input.next();
String str2 = input.next();
String[] str1a = str1.split("\\."); //这样就变成2个大数相加的问题了
String[] str2b = str2.split("\\.");
int[] zhengshu = dashuxiangjia(str1a[0],str2b[0]);
int[] xiaoshu = xiaoshuxiangjia(str1a[1],str2b[1]);
int changdu1 = str1a[1].length() - str2b[1].length() > 0 ? str1a[1].length() : str2b[1].length();
int changdu0 = str1a[0].length() - str2b[0].length() > 0 ? str1a[0].length() : str2b[0].length();
if (xiaoshu[0] != 0) {
zhengshu[0] = zhengshu[0] + xiaoshu[0]; //小数相加最多增加一位 如果第一位不位0,则说明小数相加>1, 将该值与整数第一位
}
while (zhengshu[changdu0] == 0) {
changdu0--;
}
for (int i1 = changdu0; i1 >= 0; i1--) {
System.out.print(zhengshu[i1]);
}
System.out.print(".");
for (int i = 1; i < xiaoshu.length; i++) {
System.out.print(xiaoshu[i]);
}
}
/** * 整数相加 */
public static int[] dashuxiangjia(String a,String b) {
int changdu = a.length() - b.length() > 0 ? a.length() : b.length();
int[] aint = new int[changdu];
int[] bint = new int[changdu];
for (int i1 = 0; i1 < a.length(); i1++) {
aint[a.length() - 1 - i1] = Integer.parseInt(a.substring(i1,i1 + 1));
}
for (int i1 = 0; i1 < b.length(); i1++) {
bint[b.length() - 1 - i1] = Integer.parseInt(b.substring(i1,i1 + 1));
}
int[] sum = new int[changdu + 1];
for (int i3 = 0; i3 < changdu; i3++) {
sum[i3] = aint[i3] + bint[i3];
}
for (int i4 = 0; i4 < changdu; i4++) {
sum[i4 + 1] = sum[i4] / 10 + sum[i4 + 1];
sum[i4] = sum[i4] % 10;
}
int sumchangdu = changdu;
/* while (sum[sumchangdu] == 0) { sumchangdu--; }*/
return sum;
/* System.out.print(a + " + " + b + " = "); for (int i5 = sumchangdu; i5 >= 0; i5--) { System.out.print(sum[i5]); }*/
}
/** * 小數相加 * * @param a * @param b * @return */
public static int[] xiaoshuxiangjia(String a,String b) {
int changdu = a.length() - b.length() > 0 ? a.length() : b.length();
int[] aint = new int[changdu + 1];
int[] bint = new int[changdu + 1];
for (int i1 = 0; i1 < a.length(); i1++) {
aint[i1 + 1] = Integer.parseInt(a.substring(i1,i1 + 1));
}
for (int i1 = 0; i1 < b.length(); i1++) {
bint[i1 + 1] = Integer.parseInt(b.substring(i1,i1 + 1));
}
int[] sum = new int[changdu + 1];
for (int i3 = 0; i3 <= changdu; i3++) {
sum[i3] = aint[i3] + bint[i3];
}
for (int i4 = changdu; i4 >= 1; i4--) {
sum[i4 - 1] = sum[i4] / 10 + sum[i4 - 1];
sum[i4] = sum[i4] % 10;
}
/* while (sum[sumchangdu] == 0) { sumchangdu--; }*/
return sum;
/* System.out.print(a + " + " + b + " = "); for (int i5 = sumchangdu; i5 >= 0; i5--) { System.out.print(sum[i5]); }*/
}
}