字符串实现Java大数加法
/*
题目描述
已知两个大数m和n(m,n>4294967295)
计算它们的和
假定大数最大不超过20位
使用Java答题的同学,如果使用大数类,请自己实现这个类和它的加法功能,不难的
输入
两个大数
输出
他们的和
样例输入
1000000000000000000
1000000000000000000
样例输出
2000000000000000000
利用字符串来实现大数加法
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1,s2;
Scanner in=new Scanner(System.in);
s1=in.next();//读入两个大数,以字符串形式进行存储
s2=in.next();
in.close();
int[] a=new int[20];
int[] b=new int[20];
int[] c=new int[22];
for(int i=0;i
for(int i=0;i
int Cy=0,i=0,temp=0,j=0;//Cy是进位标志
for(i=s1.length()-1;i>=0;i--)
c[j++]=a[i];
j=0;
for(i=s2.length()-1;i>=0;i--)
{
temp=c[j]+b[i]+Cy;Cy=0;
if(temp>9)
{
Cy=temp/10;//求进位
c[j++]=temp%10;
continue;
}
else
{
c[j++]=temp;
}
}
for(;Cy!=0;j++)
{
temp=Cy+c[j];Cy=0;
if(temp>9)
{
Cy=temp/10;
c[j]=temp%10;
}
else
{
c[j]=temp;
}
}
temp=0;
for( j=21;j>=0;j--)
if(c[j]==0&&temp==0)
continue;//最后结果前面的0不输出
else
{
temp=1;
System.out.print(c[j]);
}
}
}