大数加法
1.加法
//A+B问题 #define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<cstdio> #include<cstring> using namespace std; char s1[1000], s2[1000]; void add() { char s3[1000]; int len1 = strlen(s1),len2 = strlen(s2),len; if (len1<len2) len = len2; else len = len1; int i = len1 - 1, j = len2 - 1, h = 0,loc = 0,x=0; s1[len1] = '0',s2[len2] = '0'; while (len--) { s3[h] = ((s1[i] - '0') + (s2[j] - '0') + loc) % 10 + '0'; x = s3[h]-'0'; loc = ((s1[i] - '0') + (s2[j] - '0')+loc) / 10; if (i>0 && j>0 && j != len2 && i != len1) { i--, j--,h++; } else if (i <= 0 || i == len1) { j--,i = len1,h++; } else if (j <= 0 || j == len2) { i--, j = len2,h++; } else break; } if(loc) s3[h++] = loc + '0'; for (int i = h - 1; i >= 0; i--) printf("%c", s3[i]); } int main() { int cas; cin>>cas; for(int i=1;i<=cas;i++) { scanf("%s", s1); scanf("%s", s2); printf("Case %d:\n%s + %s = ",i,s1,s2); add(); cout<<endl; if(i!=cas) cout<<endl; } return 0; }
1加法(简单版)
#include<stdio.h> #include<string.h> #define MAX 1000 /*宏定义,下面遇到MAX的时候都变成1000 */ int main(void) { unsigned char arr1[MAX]={0},arr2[MAX]={0}; int len,i,len1,len2,t,j = 0; char str[MAX]; /*读入数据,并进行预处理(计算出数字位数,并反方向存放)*/ scanf("%s",str); len1 = strlen(str); for(i=0; i<len1; ++i) arr1[i] = str[len1-1-i] - '0'; scanf("%s",str); len2 = strlen(str); for(i=0; i<len2; i++) arr2[i] = str[len2-1-i] - '0'; len = (len1>len2)?len1:len2; for(i=0; i<len; i++) { t = arr1[i] + arr2[i] +j; arr1[i] = t % 10; j = t / 10; } if(j != 0) arr1[len++] = j; for(i=0; i<len; ++i) printf("%d",arr1[len-1-i]); return 0; }