面试那时候听说过大整数乘法,当时加法都够呛,要真碰到乘法肯定吓尿了,这里碰到了,想了想,写了写,也不过如此。
// LeetCode_MultiplyStrings.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(const string &str1,const string &str2)
{
string ret="";
int lenstr1 = str1.length();
int lenstr2 = str2.length();
if (lenstr1==0)
return str2;
if(lenstr2==0)
return str1;
bool flag = false;
int i = lenstr1-1, j = lenstr2-1;
while(i>=0&&j>=0)
{
int tempbit = str1[i] - '0' + str2[j] - '0';
if(flag)
tempbit++;
if (tempbit>=10)
{
tempbit = tempbit - 10;
flag = true;
}
else
flag = false;
char tempchar = tempbit + '0';
ret += tempchar;
--i;--j;
}
while(i>=0)
{
int tempbit = str1[i] - '0';
if(flag)
tempbit++;
if (tempbit>=10)
{
tempbit = tempbit - 10;
flag = true;
}
else
flag = false;
char tempchar = tempbit + '0';
ret += tempchar;
--i;
}
while(j>=0)
{
int tempbit = str2[j] - '0';
if(flag)
tempbit++;
if (tempbit>=10)
{
tempbit = tempbit - 10;
flag = true;
}
else
flag = false;
char tempchar = tempbit + '0';
ret += tempchar;
--j;
}
if(flag)
ret += "1";
reverse(ret.begin(),ret.end());
return ret;
}
string multiply(string num1, string num2) {
if(num1=="0"||num2=="0")
return string("0");
if(num1 == "") return num2;
if(num2 == "") return num1;
int lennum1 = num1.length();
int lennum2 = num2.length();
int i = lennum1 - 1,j = lennum2 - 1;
string ret = "";
for (i=lennum1-1;i>=0;i--)
{
int tempbiti = num1[i] - '0';
string onesum = "";
int flag = 0;//进位
for (j=lennum2-1;j>=0;j--)
{
int tempbit = tempbiti * (num2[j] - '0');
tempbit += flag;
flag = tempbit/10;
tempbit = tempbit%10;
char tempchar = tempbit + '0';
onesum += tempchar;
}
if (flag)
{
onesum += (flag + '0');
}
reverse(onesum.begin(),onesum.end());
for (int k=lennum1-1;k>i;k--)
{
onesum += "0";
}
ret = add(onesum,ret);
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
string str1("129"),str2("889");
while(cin>>str1&&cin>>str2)
cout<<multiply(str1,str2)<<endl;
//cout<<add(str1,str2)<<endl;
system("pause");
return 0;
}