1、加法
//blog.csdn.net/simplestbest/article/details/6788298
- #include <stdio.h>
- #include <stdlib.h>
- #include
- #define MAXSIZE 1000
- void bigadd(const char *a, const char *b, char *pret)
- {
- int ia = strlen(a)-1; //a的个位索引
- int ib = strlen(b)-1; //b的个位索引
- int carry = 0; //进位
- int sum = 0; // 每位的和
- int ret_len = ia > ib ? (ia+1) : (ib+1);
- // malloc时考虑进位和'\0'
- char *result = (char *)malloc( (ret_len + 2) * sizeof(char) );
- if( !result ) /* perror(); */ exit(-1);
- ret_len = 0;
-
- while( ia >= 0 || ib >= 0)
- {
- sum = carry;
- if(ia >= 0)
- {
- sum += a[ia--] - '0';
- }
- if(ib >= 0)
- {
- sum += b[ib--] - '0';
- }
- carry = sum/10;
- sum = sum%10;
- result[ret_len++] = sum + '0';
- }
- if(carry > 0)
- result[ret_len++] = carry + '0';
- //result[ret_len] = '\0'; Not useful.
- while(ret_len > 0)
- {
- *pret++ = result[--ret_len];
- }
- *pret = '\0';
- free(result);
- }
- int main(int argc, char *argv[])
- {
- if (argc != 3)
- {
- printf("Usage: %s a b\n", argv[0]);
- return -1;
- }
-
- char result[MAXSIZE] = {0};
- bigadd(argv[1], argv[2], result);
- printf(" %s\n + %s\n", argv[1], argv[2]);
- printf("--------------------------------\n %s", result);
- return 0;
- }
3、乘法
未测,写的有点乱。
- void bigMultiple(char *a, char *b, char *pret)
-
{
-
int xArr[MAXSIZE], yArr[MAXSIZE], result[MAXSIZE*2];
-
int len_a = strlen(a);
-
int len_b = strlen(b);
-
int i,j;
-
-
for(i = 0; i < MAXSIZE; ++i)
-
{
-
xArr[i] = 0;
-
yArr[i] = 0;
-
}
-
for(i = 0; i < MAXSIZE*2; ++i)
-
{
-
result[i] = 0;
-
}
-
-
// atoi and reversed into Arr
-
for(i = 0; i < len_a; ++i)
-
{
-
//a[0]是高位,作为xArr的最后一个数
-
xArr[len_a - 1 - i] = a[i] - '0';
-
}
-
for(j = 0; j < len_b; ++j)
-
{
-
yArr[len_b - 1 - j] = b[j] - '0';
-
}
-
-
// calculate
-
for(i = 0; i < len_a; ++i)
-
{
-
for(j = 0; j < len_b; ++j)
-
{
-
result[i+j] += a[i]*b[j];
-
}
-
}
-
for(i = 0; i < (len_a + len_b + 1); ++i)
-
{
-
if(result[i] > 0)
-
{
-
result[i+1] += result[i]/10; //进位
-
result[i] = result[i]%10;
-
}
-
}
-
// return to pret, use prev i.
-
for(; i >= 0 ; --i)
-
{
-
if(result[i] != 0)
-
break;
-
}
-
-
for(j = 0; j < i; ++j)
-
*(pre+j) = result[i-j];
-
*(pre+j) = '\0';
-
}
2、减法
.
阅读(1742) | 评论(0) | 转发(0) |