1 import java.util.Scanner; 2 3 /* 4 进行大数相加,只能对两个正数进行相加 5 */ 6 7 public class BigNumber 8 { 9 public static void main(String[] args) 10 { 11 Scanner scan=new Scanner(System.in); 12 String a,b; 13 while (scan.hasNext()) 14 { 15 BigNumber big=new BigNumber(); 16 17 a=scan.nextLine(); 18 b=scan.nextLine(); 19 20 System.out.println(big.bigNumberAdd(a,b)); 21 } 22 } 23 24 public String bigNumberAdd(String x,String y) 25 { 26 //String result=null; 27 28 char[] a=x.toCharArray(); 29 char[] b=y.toCharArray(); 30 31 int lenA=a.length; 32 int lenB=b.length; 33 34 int len=lenA>lenB?lenA:lenB; 35 int[] result=new int[len+1]; 36 37 //字符串反转 38 char[] A=new char[lenA]; 39 char[] B=new char[lenB]; 40 for (int i=0;i<lenA;i++) 41 { 42 A[i]=a[lenA-i-1]; 43 } 44 45 for (int j=0;j<lenB;j++) 46 { 47 B[j]=b[lenB-j-1]; 48 } 49 50 //对应数字相加 51 int aInt,bInt; 52 for (int i=0;i<len+1;i++) 53 { 54 aInt=i<lenA?A[i]-‘0‘:0; 55 bInt=i<lenB?B[i]-‘0‘:0; 56 57 result[i]=aInt+bInt; 58 } 59 60 //将对应数字结果超过10 61 for (int j=0;j<len+1;j++) 62 { 63 if (result[j]>=10) 64 { 65 //将对应位置与进位相加,并进行保存 66 result[j+1]=result[j]/10+result[j+1]; 67 result[j]=result[j]%10; 68 } 69 } 70 71 //将结果对应为0的位置取消掉 72 StringBuilder sb=new StringBuilder(); 73 boolean flag=true;//防止结果集中的地位出现0 74 for (int i=len;i>=0;i--) 75 { 76 if (result[i]==0&&flag) 77 { 78 79 } 80 else 81 { 82 sb.append(result[i]); 83 flag=false; 84 } 85 } 86 87 return sb.toString(); 88 //return result; 89 } 90 }
时间: 2024-12-11 02:08:31