HDU1002大数加法
大数加法
c++版:
1 #include <map> 2 #include <set> 3 #include <stack> 4 #include <queue> 5 #include <cmath> 6 #include <ctime> 7 #include <vector> 8 #include <cstdio> 9 #include <cctype> 10 #include <cstring> 11 #include <cstdlib> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 #define INF 0x3f3f3f3f 16 #define MAX(a,b) (a > b ? a : b) 17 #define MIN(a,b) (a < b ? a : b) 18 #define mem0(a) memset(a,0,sizeof(a)) 19 20 typedef long long LL; 21 const double eps = 1e-12; 22 const int MAXN = 1005; 23 const int MAXM = 5005; 24 25 char a[MAXN], b[MAXN]; 26 27 void slove() 28 { 29 int lena = strlen(a); 30 int lenb = strlen(b); 31 strrev(a); strrev(b); 32 int p = 0; 33 while(a[p] || b[p]) 34 { 35 if(a[p]>='0') a[p] -= '0'; 36 if(b[p]>='0') b[p] -= '0'; 37 a[p] += b[p]; 38 a[p+1] += a[p]/10; 39 a[p] = a[p] % 10 + '0'; 40 p++; 41 } 42 strrev(a); 43 } 44 45 int main() 46 { 47 int T, Case=0; 48 scanf("%d", &T); 49 while(T--) 50 { 51 mem0(a); mem0(b); 52 scanf("%s %s%*c", a, b); 53 printf("Case %d:\n", ++Case); 54 printf("%s + %s = ", a, b); 55 slove(); 56 printf("%s\n", a); 57 if(T) printf("\n"); 58 } 59 return 0; 60 }
java版:
1 import java.math.*; 2 import java.util.*; 3 import java.io.*; 4 5 public class Main{ 6 7 public static void main(String[] args) throws Exception 8 { 9 10 Scanner cin = new Scanner(new BufferedInputStream(System.in)); 11 int T = cin.nextInt(); 12 int c = 1; 13 while((T--) != 0)//多组输入 14 { 15 BigInteger a,b; 16 a = cin.nextBigInteger(); 17 b = cin.nextBigInteger(); 18 System.out.println("Case " + (c++) + ":"); 19 System.out.println(a + " + " + b + " = " + a.add(b)); 20 if(T != 0) System.out.println(); 21 } 22 } 23 }