大整数加法
来源:互联网 发布:常见网络诈骗手段 编辑:程序博客网 时间: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
- 大整数加法
- 大整数加法
- 高精度 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法计算
- zoj1292大整数加法
- 大整数加法
- 大整数加法
- 大整数加法函数
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 【算法】大整数加法
- 梵蒂冈三个发广告大放送梵蒂冈
- n元一次不定方程
- 一些简单的特效 鼠标悬停 鼠标移动 和 图标特效
- 使用Jenkins进行持续集成(二)-配置篇
- 分区索引
- 大整数加法
- 用canvas完成超炫酷的数字时钟
- android:windowSoftInputMode属性详解
- PHP持续集成实践
- java 中不常见的关键字:strictfp,transient
- Hadoop的Mapreduce运行原理详解
- (hdu step 3.2.2)Common Subsequence(简单dp:求最长公共子序列的长度)
- Java客户端调用Https Webservice
- 解读TestBird手游兼容性测试白皮书