昨天写了个大数加法,说下原理。
数字保存肯定是得用字符串了,然后逐位从char转换成int型,接着进行运算,把运算的结果保存到一个字符串中。
然后对字符串进行判断是一位还是两位,如果是一位,就直接修改结构体中的字符串,如果是两位,就向保存的进位数字的数组中加1(我是用分配两个大小相同的数组来做的,一个用来存储要运算的数,一个保存要进位的数,其实不用这样,给个临时变量就行了,不过这是后来想明白的,呵呵)
不多说了,看代码吧:
#include
#include
#include
#include
#include
#define NUM_LEN 500
#define ctoi(c) (c-48)
//#define max(a,b) (((a) > (b)) (a) : (b))
//itoa
struct _big_num;
typedef _big_num big_num;
typedef big_num* pbig_num;
struct _big_num
{
//用来标识字符串中共有多少位的数字
int index;
//标识最大支持多少位
int maxsize;
char *buff;
//用来表示进位
char *nums;
};
//将整形
/*int ctoi(int c)
{
return (c-48);
}*/
//创建大数结构体,并分配内存,清零
pbig_num big_num_create(char *num)
{
pbig_num p = NULL;
p = (pbig_num)malloc(sizeof(*p));
assert(p);
p->buff = (char*)malloc(NUM_LEN);
p->nums = (char*)malloc(NUM_LEN);
//memset(p)
memset(p->buff,0,NUM_LEN);
memset(p->nums,0,NUM_LEN);
p->maxsize = NUM_LEN;
p->index = 0;
if (num != NULL)
{
strncpy(p->buff,num,NUM_LEN);
p->index = strlen(num);
}
return p;
}
//释放资源
void big_num_free(pbig_num *b)
{
assert(b);
free((*b)->buff);
free((*b)->nums);
free((*b));
}