HDOJ1002大数相加
- 问题
- I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
- 输入
- The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
- 输出
- For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
用以前C/C++的思维,我第一个想到的是这个
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int T=scanner.nextInt();
for(int i=0;i<T;i++) {
String A=scanner.next();
String B=scanner.next();
int lenA=A.length();
int lenB=B.length();
int lenMax=lenA>lenB ? lenA : lenB;
char[] C=new char[lenMax];
int lenAA=lenA;
int lenBB=lenB;
int before=0;
for(int j=0;j<lenMax;j++) {
if(lenAA>0 && lenBB>0) {
int s=A.charAt(lenA-1-j)+B.charAt(lenB-1-j)-48-48;
if((s+before)<10) {
C[lenMax-1-j]=(char)(s+before+48);
before=0;
}else {
C[lenMax-1-j]=(char)(s+before-10+48);
before=1;
}
}
}
System.out.println("Case "+(i+1)+":");
System.out.print(A+" + "+B+" = ");
if(before>0) System.out.print(before);
System.out.println(C);
System.out.println();
}
}
}
为了入门java所以都用java写,功能实现了,但OJ平台没通过,不过我也不是为了比赛,只是想练习下java,就不管那么多了,然后才发现java有BigInteger和BigDecimal类可实现任意精度的整数和浮点运算,且有专门的处理函数,啊,好方便,简直了,然后就是最后的实现。
实现
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int T=scanner.nextInt();
for(int i=0;i<T;i++) {
BigInteger A=scanner.nextBigInteger();
BigInteger B=scanner.nextBigInteger();
System.out.println("Case "+(i+1)+":");
System.out.println(A+" + "+B+" = "+A.add(B));
if(i<(T-1)) {
System.out.println(); //格式要求
}
}
}
}