[ACM]HDU Problem 1002 + Java
import java.util.Scanner; import java.math.BigDecimal; public class Main { public static void main(String args[]){ Scanner input = new Scanner(System.in); int T = input.nextInt(); for(int i = 1; i <= T; i++){ BigDecimal a = input.nextBigDecimal(); BigDecimal b = input.nextBigDecimal(); BigDecimal sum = a.add(b); System.out.println("Case " + i + ":"); System.out.print(a + " + " + b + " = " + sum); if(i != T){ System.out.println(); } System.out.println(); } } }
此外我还按照手动演算进位的方法写了一种,有点绕,但是也AC了,仅供参考。
import java.util.Scanner; public class Main { public static void main(String args[]){ Scanner input = new Scanner(System.in); int T = input.nextInt(); int cnt = T; while(T != 0){ int sum[] = new int[1001]; sum[0] = 0; String sa = input.next(); String sb = input.next(); int la = sa.length(); int lb = sb.length(); int d = 0; int length = la > lb ? (la+1) : (lb+1); for(int i = length-1; i > 0; i--){ int sa1, sb1; if(la > 0){ sa1 = sa.charAt(la-1) - '0'; } else{ sa1 = 0; } if(lb > 0){ sb1 = sb.charAt(lb-1) - '0'; } else{ sb1 = 0; } sum[i] = (sa1 + sb1 + d) % 10; d= (sa1 + sb1 + d) / 10; la--; lb--; } sum[0] = d; StringBuffer str = new StringBuffer(); if(sum[0] != 0) //System.out.print(sum[0]); str.append(sum[0]); for(int i = 1; i < length; i++){ //System.out.print(sum[i]); str.append(sum[i]); } System.out.println("Case " + (cnt-T+1) + ":"); System.out.print(sa + " + " + sb + " = " + str); if(T != 1){ System.out.println(); } System.out.println(); T--; } input.close(); } }