大数相乘
给定两个数据“1234”与“3456”
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <assert.h>
using namespace std;
struct bigcheng2
{
string a;
string b;
string result_str;
};
//void reverse_data( string &data);//字符串反转
//void multiply2(bigcheng2 &tempcheng2);//字符串模拟相乘
void reverse_data( string &data)
{
char temp = '0';
int start=0;
int end=data.size()-1;
assert( data.size()&& start <= end );
while ( start < end )
{
temp = data[start];
data[start++] = data[end];
data[end--] = temp;
}
}
void multiply2(bigcheng2 &tempcheng2)
{
reverse_data(tempcheng2.a);//字符串反转
reverse_data(tempcheng2.b);
int c=0;
string temp(tempcheng2.a.size()+tempcheng2.b.size(),'0');//将temp全部初始化为0字符
for (unsigned int i=0;i<tempcheng2.a.size();i++)
{
unsigned int j;
for (j=0;j<tempcheng2.b.size();j++)
{
c+=temp[i+j]-'0'+(tempcheng2.a[i]-'0')*(tempcheng2.b[j]-'0');//注意temp[i+j]可能保存有上一次计算的结果
temp[i+j]=(c%10)+'0';//将结果转换为字符
c=c/10;
}
while(c)
{
temp[i+j++]+=c%10;//temp里已存字符
c=c/10;
}
}
for (int i=temp.size()-1;i>=0;i--)
{
if (temp[i]!='0')
break;
else
temp[i]='\0';
}
reverse_data(temp);//结果?字á?符¤?串??反¤??转áa
tempcheng2.result_str=temp;
}
int main()
{
bigcheng2 tempcheng2;
string a,b;
cin>>a>>b;
tempcheng2.a=a;
tempcheng2.b=b;
multiply2(tempcheng2);
cout<<tempcheng2.result_str<<endl;
system("pause");
return 0;
}
大数相加
bool check(char *p)
{
if (!p)
{
return 1;
}
int i=0;
while(p[i]!='\0')
{
if (p[i]<'0'||p[i]>'9')
{
return 1;
}
else ++i;
}
return 0;//合法
}
char* bigadd(char *p1,char *p2)
{
if (check(p1)||check(p2))
{
throw exception("Invalid input!");
}
int len1=strlen(p1);
int len2=strlen(p2);
int len3=max(len1,len2)+1;
char *p3=new char[len3+1];
memset(p3,'0',len3);
p3[len3]='\0';
int index1=len1-1,index2=len2-1,index3=len3-1;
int carry=0;
while(index1>=0&&index2>=0)
{
int num=p1[index1--]-'0'+p2[index2--]-'0'+carry;
if (num>=10)
{
carry=1;
num-=10;
}
else
carry=0;
p3[index3--]=num+'0';
}
while(index1>=0)
{
int num=p1[index1--]-'0'+carry;
if (num>=10)
{
carry=1;
num-=10;
}
else
carry=0;
p3[index3--]=num+'0';
}
while(index2>=0)
{
int num=p1[index2--]-'0'+carry;
if (num>=10)
{
carry=1;
num-=10;
}
else
carry=0;
p3[index3--]=num+'0';
}
p3[index3]=carry?'1':'0';
return p3;
}