A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 305668 Accepted Submission(s): 59062
2 1 2 112233445566778899 998877665544332211
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
分析:本体表面上看只是普通的a+b题,要注意的是,输入的数可能大到整数甚至是浮点数无法表示,因此这一题有两种做法,如下。
做法一:用字符串和字符数组做
这种方法比较麻烦一些,有点绞思维
import java.util.Scanner; class Main{ public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int c=0; int num=0; while (n-->0){ num++; String a=input.next(); String b=input.next(); char cha[]=a.toCharArray(); char chb[]=b.toCharArray(); int A[]=new int[1000]; int B[]=new int[1000]; int C[]=new int[1000]; for (int i=0;i<cha.length;i++){ A[i]=cha[cha.length-1-i]-48; } for (int i=0;i<chb.length;i++){ B[i]=chb[chb.length-1-i]-48; } int s=0; for (int i=0;i<1000;i++){ s+=A[i]+B[i]; C[i]=s%10; s/=10; } String str=""; int j; for (j=999;j>=0;j--){ if (C[j]>0){ break; } } for (int i=j;i>=0;i--){ str+=C[i]; } if (c++>0){ System.out.println(); } System.out.println("Case "+num+":"); for (int i=0;i<cha.length;i++){ System.out.print(cha[i]); } System.out.print(" + "); for (int i=0;i<chb.length;i++){ System.out.print(chb[i]); } System.out.println(" = "+str); } } }
这种就非常方便,且好懂,省时(关于大数详情请见本博客“Java之------大数(BigInteger,BigDecimal)”点击打开链接)
import java.math.BigInteger; import java.util.Scanner; class Main{ public static void main(String[] args) { Scanner input=new Scanner(System.in); int t=input.nextInt(); int blank=0; int num=1; while (t-->0){ if (blank++>0){ System.out.println(); } String aStr=input.next(); String bStr=input.next(); BigInteger a=new BigInteger(aStr); BigInteger b=new BigInteger(bStr); BigInteger c=a.add(b); String cStr=c.toString(); System.out.println("Case "+num+":"); System.out.println(aStr+" + "+bStr+" = "+cStr); num++; } } }