大整数加法

来源:互联网 发布:常见网络诈骗手段 编辑:程序博客网 时间:2024/05/19 23:12

a: "15149697207"

b: "68021668610"

a、b两个字符串,求a、b的和。


思路:数字都是从低位开始相加,数组习惯从0下标开始取值,因此先把字符串进行翻转,再进行求和,最后将求和得到的结果翻转就是最后结果。


字符串翻转函数:

int reverse_str(char *str){int i,n;int len = 0;char *str_p = str;char tmp = 0;if (str == NULL) {return -1;}while (*str_p++) {len++;}if (len == 0) {return -1;}for (n = len - 1, i = len - n -1; n >= i; n--, i++ ) {tmp = str[n];str[n] = str[i];str[i] = tmp;}return 0;}

求和函数:

int add_big_num(char *a, char *b, char *output){char *a_p = a;char *b_p = b;char *output_p = output;int tmp = 0;/*进位*/int plus = 0;/*每位加起来的总和,解决00+0=00的异常情况*/int total = 0;if ((a == NULL) || (b == NULL) || (output == NULL)) {return -1;}if (reverse_str(a)) {return -1;}if (reverse_str(b)) {return -1;}/*运算长度相同的那部分*/while ((*a_p != '\0') && (*b_p != '\0')) {tmp = (*a_p++ - '0') + (*b_p++ - '0') + plus;if (tmp > 9) {tmp %= 10;plus = 1;} else {plus = 0;}total += tmp;*output_p++ = '0' + tmp;}/*运算a字符串剩余的部分*/while (*a_p != '\0') {tmp = *a_p++ - '0' + plus;if (tmp > 9) {tmp %= 10;plus = 1;} else {plus = 0;}total += tmp;*output_p++ = '0' + tmp;}/*运算b字符串剩余的部分*/while (*b_p != '\0') {tmp = *b_p++  - '0' + plus;if (tmp > 9) {tmp %= 10;plus = 1;} else {plus = 0;}total += tmp;*output_p++ = '0' + tmp;}/*避免999+1得到000的情况*/if (plus) {*output_p++ = '1';}if (total == 0) {output[0] = '0';output[1] = '\0';}reverse_str(output);return 0;}



0 0
原创粉丝点击