用字串儲存兩個大數。 把加法分解成: 一,同一位上為 (a+b)%10 二,進位(a+b)/10 ,三,把第一數+進位
感覺是遞迴了。但可以用迴圈在代替。
大數相乘也差不多,第二數的每一位元都與第一個數每一位相乘,然後相加起來.
以下我們假設兩個字串裡都是數字,之裡不做判斷了.
為瞭解題方便,我還把數字都移到數組的右端,方便相加.不足是會浪費一些時間
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAXSIZE 20//判斷 字串中是否全是0int isZero(const char* s){if (s == NULL || s == '\0')return 1;while (*s != '\0'){if (*s++ != '0')return 0;}return 1;}//假設len >= strlen(src)+1//把src中的字串把到dest的右端,前面補0char* rcpy_addZero(char *dest, int len, const char *src){int i, srcLen = 0;if (src == NULL)srcLen = 0;elsesrcLen = strlen(src);if(len < srcLen+1) return NULL;dest[len - 1] = '\0';for (i = 0; i < len - srcLen - 1; i++){dest[i] = '0';}strncpy(dest + len - srcLen - 1, src, srcLen);return dest;}//我們假設兩個數都不會超過MAXSIZE-2位(兩數組的長度不超過MAXSIZE-1),ps:最後一位用來放'\0',第一位用來放 進位//只限兩個正整數char* bigNumAdd(const char* a, const char *b,char *result){//s1的長度更大char s1[MAXSIZE],s2[MAXSIZE];int i,s;if (a == NULL && b == NULL)return NULL;//pSum = (char *) malloc(sizeof(char) * MAXSIZE);/************kit start************/rcpy_addZero(s1,MAXSIZE,a);rcpy_addZero(s2,MAXSIZE,b);while (isZero(s2)==0){for (i=0;i<MAXSIZE-1;i++){s = s1[i] + s2[i] - '0' - '0';if (s > 9){s1[i] = s - 10 + '0';i && (s2[i-1]='1'); // i=0時 ,不進位}else{s1[i] = s + '0';i && (s2[i-1]='0');}}s2[i-1]='0';}strcpy(result,s1);return result;}//左移n位,補0void LeftShift(char* s,int n){if(s==NULL) return;int i=0;int len=strlen(s);for(i=n;i<len;i++){s[i-n]=s[i];}for(i=0;i<n;i++){s[len-1-i]='0';}}//大數相乘 兩個字串必須為整數char *bigNumsMultiply(const char *a,const char *b,char *result){int isNegative=0,i,k,s;char s1[MAXSIZE],s2[MAXSIZE],sum[MAXSIZE],carry[MAXSIZE];carry[MAXSIZE-2]='0';if(a==NULL || b==NULL) return NULL;if(a[0] == '+' || a[0] == '-' || b[0] == '+' || b[0] == '-'){if((a[0]=='-' || b[0]=='-') && a[0]!=b[0]) isNegative=1;}if (a[0] == '+' || a[0] == '-')rcpy_addZero(s1, MAXSIZE, a + 1);elsercpy_addZero(s1, MAXSIZE, a );if (b[0] == '+' || b[0] == '-')rcpy_addZero(s2, MAXSIZE, b + 1);elsercpy_addZero(s2, MAXSIZE, b);result[0] = '\0';carry[MAXSIZE - 2] = '0';carry[MAXSIZE - 1] = '\0';for(i=MAXSIZE-2;i>=0;i--) //s2{for(k=MAXSIZE-2;k>=0;k--) //s1{s=(s1[k]-'0')*(s2[i]-'0');sum[k]=s%10 + '0';k && (carry[k-1]=s/10 + '0'); //防止最高位進位}bigNumAdd(sum,carry,sum);bigNumAdd(sum,result,result);LeftShift(s1,1); //左移一位}if(isNegative) result[0]='-';return result;}int main(void){char pSum[MAXSIZE];printf("Add:%s\n",bigNumAdd("87968645654213","5645461359",pSum));printf("Mutiply:%s",bigNumsMultiply("-1232424465","-4566228",pSum));return 0;}