算法提高 P1001
来源:互联网 发布:知乎平均学历 编辑:程序博客网 时间:2024/05/16 12:37
当两个比较大的整数相乘时,可能会出现数据溢出的情形。为避免溢出,可以采用字符串的方法来实现两个大数之间的乘法。具体来说,首先以字符串的形式输入两个整数,每个整数的长度不会超过8位,然后把它们相乘的结果存储在另一个字符串当中(长度不会超过16位),最后把这个字符串打印出来。例如,假设用户输入为:62773417和12345678,则输出结果为:774980393241726.
输入:
62773417 12345678
输出:
774980393241726
模拟竖式乘法运算,大数乘法
#include <iostream>#include"string.h"using namespace std;void mul(string ch1, string ch2){ int len1=ch1.size(),len2=ch2.size(); if((len1==1&&ch1[0]=='0')||(len2==1&&ch2[0]=='0')) { cout<<"0"<<endl; return ; } string ch3; for(int i=0;i<1000000;i++) ch3+='\0'; int i,j,carry; for (i=0; i<len1; i++) { for (j=0; j<len2; j++)// { ch3[i+j]=ch3[i+j]+(ch1[i]-'0')*(ch2[j]-'0');//这里用字符型表示ch3要注意 if (ch3[i+j]>9&&(i+j)>0) { ch3[i+j-1]+=ch3[i+j]/10; ch3[i+j]=ch3[i+j]%10; } } } for (i=len1+len2-1; i>0; --i)//防止上面进位时大于9 { if (ch3[i]>9) { ch3[i-1]=ch3[i-1]+ch3[i]/10; ch3[i]%=10; } } if (ch3[0]>9)//if (ch[3]>99) { cout<<ch3[0]/10; ch3[0]=ch3[0]%10; } for (i=0; i<len1+len2-1; i++) cout<<char(ch3[i]+48); cout<<endl;}int main(){ string ch1,ch2; while (cin>>ch1>>ch2) { mul(ch1,ch2); } return 0;}
0 0
- 算法提高 P1001
- 算法提高 P1001
- 算法提高 P1001
- 算法提高 P1001
- 蓝桥杯 算法提高 P1001
- 算法提高 P1001
- 算法提高 P1001
- 算法提高 P1001
- 算法提高 P1001
- 算法提高 ADV-197 P1001
- 算法提高 P1001 (大数乘法)
- 算法提高 P1001 (大数相乘)
- 蓝桥杯 ADV-197 算法提高 P1001
- 蓝桥杯 ADV-197 算法提高 P1001
- 2016蓝桥杯算法提高——P1001(大数乘法)
- P1001 蓝桥杯算法提高-用字符串处理大数乘法
- p1001
- p1001
- c++ operator 问题
- G-Expanding Rods
- 模板编程
- CSS那些事
- (0044) iOS 开发之SDWebImage 深度学习其源码和原理
- 算法提高 P1001
- C语言文件读写操作
- Unity 几种优化建议
- 什么是BSS段和c语言程序如何变成可执行的文件
- 欢迎使用CSDN-markdown编辑器
- Fragment
- 2048
- 【剑指offer】字符流中第一个不重复的字符
- 1009. 说反话 (20) PAT