大整数的加法
来源:互联网 发布:知子之来之 杂佩以赠之 编辑:程序博客网 时间:2024/04/19 03:12
突然心血来潮,拿着大整数来消遣了一下。
第一种方法:
讲字符数组一一对应的转换到整型数组中,然后进行相加运算
代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;#define M 1000char str1[M+10], str2[M+10];int num1[M+10], num2[M+10], num[M+10];int Plus(){ int len = MAX(strlen(str1), strlen(str2)); for(int i=1; i<=len; ++i){ num[i] = num[i-1]/10+num1[i]+num2[i]; num[i-1] %= 10; }}int main(){ while(~scanf("%s%s", str1, str2)){ int len; memset(num1,0,sizeof(num1)); memset(num2,0,sizeof(num2)); len = strlen(str1); for(int i=0; i<len; ++i){ num1[len-i] = str1[i]-'0'; } len = strlen(str2); for(int i=0; i<len; ++i){ num2[len-i] = str2[i]-'0'; } Plus(); int i=M+10; int len = MAX(strlen(str1), strlen(str2)); for(int j=i; j>0; --j) printf("%d", num[j]); printf("\n"); } return 0;}
第二种方法:
将数据压缩写入整型数组中,每4位写入一个数组中。
代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;#define M 1000char str1[M+10], str2[M+10];int num1[M+10], num2[M+10], num[M+10];int Plus(){ int len = MAX((strlen(str1)/4),(strlen(str2)/4))+1; for(int i=1; i<=len; ++i){ num[i] = num[i-1]/10000+num1[i]+num2[i]; num[i-1] %= 10000; }}int main(){ while(~scanf("%s%s", str1, str2)){ memset(num1, 0, sizeof(num1)); memset(num2, 0, sizeof(num2)); int len = strlen(str1); int i,j; for(i=len-1,j=1; i>=3; i-=4){ for(int k=3; k>=0; --k) num1[j] = (str1[i-k]-'0')+num1[j]*10; j++; } if(i==0) num1[j] = str1[i]-'0'; else if(i==1) num1[j] = (str1[i-1]-'0')*10+str1[i]-'0'; else if(i==2) num1[j] = ((str1[i-2]-'0')*10+str1[i-1]-'0')*10+str1[i]-'0'; len = strlen(str2); for(i=len-1,j=1; i>=3; i-=4){ for(int k=3; k>=0; --k) num2[j] = (str2[i-k]-'0')+num2[j]*10; j++; } if(i==0) num2[j] = str2[i]-'0'; else if(i==1) num2[j] = (str2[i-1]-'0')*10+str2[i]-'0'; else if(i==2) num2[j] = ((str2[i-2]-'0')*10+str2[i-1]-'0')*10+str2[i]-'0'; Plus(); len = MAX((strlen(str1)/4),(strlen(str2)/4))+1; printf("%d", num[len]); for(i = len-1; i>0; --i){ printf("%04d", num[i]); } printf("\n"); } return 0;}
如有哪里有问题,请留言!
0 0
- 大整数的加法
- 大整数的加法
- 大整数的加法
- 大整数的加法问题
- 大整数的加法运算
- 用数组存储大整数,实现大整数的加法
- 任意长度的高精度大整数加法
- 任意长度的高精度大整数加法
- 大整数的乘法、加法、减法
- 大整数加法的源代码合集!
- 大整数的加法、减法和乘法
- 大整数的乘法与加法
- 大整数的加法和乘法运算
- 任意长度的高精度大整数加法
- Problem B: 大整数的加法运算
- Problem I: 大整数的加法运算
- Problem A: 大整数的加法运算
- 大整数加法
- HTML5 Inline SVG
- Pentaho Report Designer 源码分析过程
- js中的数组Array用法
- (精!)多屏幕多分辨率的支持和一些概念
- 404计算机毕业设计
- 大整数的加法
- 九度OJ 1450 产生冠军
- "或"的扩张,use_concat以及no_expand提示使用
- 第一个简单的程序——Struts 2 官方文档翻译(Struts 2官方文档中文版)
- 什么是回调函数(callback function)
- java 中hashcode 与 equals的关系
- SQL索引工作原理
- JVM系列文章(1):JVM内存分配
- 一个默默奋斗的coding小伙