高精度算法
高精度加法
//1.输入两个整数a,b,输出他们的和(a,b≤10^9)
//2.输入两个整数a,b,输出他们的和(a,b≤10^500)
/*分析:int : -2^31~2^31-1,数量级为10^9
long long:-2^63~2^63-1,数量级为10^18
解决方法:用数组模拟高精度*/
算法核心:
- c[i] += a[i] + b[i];
- c[i+1] = c[i] / 10;
- c[i] = c[i] % 10;
//1.字符串读入 //2.字符串转数组 //3.竖式加法 //4.消前导零 //5.倒序输出
Java的高精度加法
import java.math.BigInteger;
import java.util.Scanner;
public class HighPrecisionAdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String x = scanner.nextLine();
String y = scanner.nextLine();
BigInteger bigx = new BigInteger(x);
BigInteger bigy = new BigInteger(y);
BigInteger sum = bigx.add(bigy);
System.out.println("和为"+sum);
}
}
C++的高精度加法
#include <bits/stdc++.h>
using namespace std;
string x,y;
int a[10000],b[10000],c[10000],la,lb,lc;
int main(){
cin >> x >> y;
la = x.length();
lb = y.length();
for(int i = 0; i < la ; i++){
a[la-i] = x[i] - '0';
}
for(int i = 0; i < la ; i++){
b[lb-i] = y[i] - '0';
}
lac = max(la,lb);
for(int i = 1; i <= lc ; i++){
c[i] += a[i] + b[i];
c[i+1] = c[i] / 10;
c[i] %= 10;
}
if(c[lc+1] > 0)lc++;
for(int i = lc ; i >= 1 ; i--)
count << c[i];
}