AcWing 791. 高精度加法Java 简单模拟
原题链接
简单
作者:
还想听你的故事
,
2021-03-23 17:01:42
,
所有人可见
,
阅读 294
BigInteger工具类
import java.math.BigInteger;
import java.util.*;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
BigInteger a=new BigInteger(s1);
BigInteger b=new BigInteger(s2);
System.out.println(a.add(b).toString());
}
}
模拟高精度
import java.math.BigInteger;
import java.util.*;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
int i=s1.length()-1,j=s2.length()-1;
StringBuilder sb=new StringBuilder();
int carry=0;
while(i>=0||j>=0||carry!=0){
if(i>=0) carry+=s1.charAt(i--)-'0';
if(j>=0) carry+=s2.charAt(j--)-'0';
sb.append(carry%10);
carry/=10;
}
System.out.println(sb.reverse().toString());
}
}