高精度加法:
两个整数相加:
#include <cstdio> #include <cstring> using namespace std; const int MAX=1001; void big_add(char a[],char b[],char c[]) { int i,e=0,d; int len1=strlen(a); int len2=strlen(b); for(i=0;i<len1/2;i++) { char t=a[i];a[i]=a[len1-1-i];a[len1-1-i]=t; } for(i=0;i<len2/2;i++) { char t=b[i];b[i]=b[len2-1-i];b[len2-1-i]=t; } for(i=0;i<len1&&i<len2;i++) { d=a[i]-'0'+b[i]-'0'+e; c[i]=d%10+'0'; e=d/10; } if(i<len1) for(;i<len1;i++) { d=a[i]-'0'+e; c[i]=d%10+'0'; e=d/10; } else for(;i<len2;i++) { d=b[i]-'0'+e; c[i]=d%10+'0'; e=d/10; } if(e) c[i++]=e+'0'; c[i]=0; int len3=i; for(i=0;i<len3/2;i++) { char t=c[i];c[i]=c[len3-1-i];c[len3-1-i]=t; } } int main() { char a[MAX],b[MAX],c[MAX]; while(scanf("%s%s",a,b)!=-1) { big_add(a,b,c); printf("%s\n",c); } return 0; }
不限制正负:
#include<stdio.h> #include<stdlib.h> #include<string.h> char A[10005]; char B[10005]; int fa, fb; void swap(char *a, int i, int j) { char t = a[i]-'0'; a[i] = a[j]-'0'; a[j] = t; } void add(char *a, char *b) { int la = strlen(a),lb = strlen(b); int i,j,c=0,s,l; for(i=fa,j=la-1; i<=j; ++i,--j) swap(a,i,j); for(i=fb,j=lb-1; i<=j; ++i,--j) swap(b,i,j); for(i=fa; i<la||i<lb; ++i) { s = a[i] + b[i] + c; c = s/10; a[i] = s%10; } a[i] = c; l = c ? i : i-1; if(fa) printf("-"); for(i=l; i>=fa; --i) printf("%d", a[i]); } int cmp(char *a, char *b) { int i,j,la,lb; la = strlen(a); lb = strlen(b); if(la-fa>lb-fb) return 1; else if(la-fa<lb-fb) return 0; else { for(i=0; i<la&&a[i+fa]==b[i+fb]; ++i); return a[i+fa]>b[i+fb]; } } void minus(char *a, char *b) { char *t; int i,j,ft,la,lb,c,l,s; if(!cmp(a,b)) { t=a; a = b; b = t; ft = fa; fa = fb; fb = ft; } la = strlen(a); lb = strlen(b); for(i=fa,j=la-1; i<=j; ++i,--j) swap(a,i,j); for(i=fb,j=lb-1; i<=j; ++i,--j) swap(b,i,j); c = 0; l = -1; for(i=0; i+fa<la; ++i) { s = a[i+fa]-b[i+fb]-c>=0 ? 0 : 1; a[i+fa] = (10+a[i+fa]-b[i+fb]-c)%10; l = a[i+fa] ? i+fa : l; c = s; } if(l<0) printf("0"); else { if(fa) printf("-"); for(i=l; i>=fa; --i) printf("%d", a[i]); } } int main() { scanf("%s%s", A, B); fa = ('-'==A[0]); fb = ('-'==B[0]); if(fa^fb) minus(A,B); else add(A,B); }
java版:
import java.util.*; import java.io.*; import java.lang.String; import java.math.BigDecimal; public class p1036 { public static void main(String[] args) { String s1,s2; Scanner cin = new Scanner(System.in); s1 = cin.next(); s2 = cin.next(); BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); System.out.println(b1.add(b2)); cin.close(); } }