您的函数实现仅限于单个数字,但您正在接受字符串(可能是多个数字。
如果您只想乘以个位数,请将您的签名更改为
int singleMultiply(char s1, char s2)
{
return (s1-'0')*(s2-'0');
}
int main()
{
cout << singleMultiply('5','4');
return 0;
}
如果你想更通用:
int singleMultiply(string s1, string s2)
{
// deprecated method, but still the easiest to understand
//return atoi(s1.c_str()) * atoi(s2.c_str());
// updated method
long l1 = strtol(s1.c_str(), NULL, 10);
long l2 = strtol(s2.c_str(), NULL, 10);
return l1 * l2;
}
int main()
{
cout << singleMultiply("50", "40");
return 0;
}
编辑:在你的编辑之后,很明显你做的工作比你需要的要多得多。 atoi
/strtol
将为您进行整数转换(并且比您尝试做的更好)。
我有一些时间可以消磨,所以我认为这就是你想要做的(虽然,我不知道你为什么想要):
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
std::string karatsuba(std::string lhs, std::string rhs)
{
if (lhs.length() != rhs.length())
{
if (lhs.length() < rhs.length())
{
int diff = rhs.length() - lhs.length();
lhs.insert(0, diff, '0');
}
else
{
int diff = lhs.length() - rhs.length();
rhs.insert(0, diff, '0');
}
}
if (lhs.length() == 1 && rhs.length() == 1)
{
long l = std::strtol(lhs.c_str(), NULL, 10);
long r = std::strtol(rhs.c_str(), NULL, 10);
long ret = l * r;
std::stringstream ss;
ss << ret;
return ss.str();
}
int m = lhs.length();
int midpoint = m / 2;
std::string lowlhs(lhs.begin() + midpoint, lhs.end());
std::string lowrhs(rhs.begin() + midpoint, rhs.end());
std::string highlhs(lhs.begin(), lhs.begin() + midpoint);
std::string highrhs(rhs.begin(), rhs.begin() + midpoint);
long addLhs = std::strtol(lowlhs.c_str(), NULL, 10) + std::strtol(highlhs.c_str(), NULL, 10);
long addRhs = std::strtol(lowrhs.c_str(), NULL, 10) + std::strtol(highrhs.c_str(), NULL, 10);
std::stringstream ssL;
std::stringstream ssR;
ssL << addLhs;
ssR << addRhs;
std::string sZ0 = karatsuba(lowlhs, lowrhs);
std::string sZ1 = karatsuba(ssL.str(), ssR.str());
std::string sZ2 = karatsuba(highlhs, highrhs);
long z0 = std::strtol(sZ0.c_str(), NULL, 10);
long z1 = std::strtol(sZ1.c_str(), NULL, 10);
long z2 = std::strtol(sZ2.c_str(), NULL, 10);
long highOrder = static_cast<long>(std::pow(10.0, static_cast<double>(m)));
long lowOrder = static_cast<long>(std::pow(10.0, static_cast<double>(m / 2)));
long result = (z2 * highOrder) + ((z1 - z2 - z0) * lowOrder) + z0;
std::stringstream ss;
ss << result;
return ss.str();
}
int main()
{
std::string lhs = "20";
std::string rhs = "45";
std::string result = karatsuba(lhs, rhs);
std::cout << "Multiplied: " << lhs << " x " << rhs << " = " << result << std::endl;
return 0;
}