【C++】利用加法实现string的乘法
#include<string>
#include<algorithm>
using namespace std;
#define MAXINT 1000000000
//写一个字符串的乘法
//加法
string stradd(string a, string b) {
if (a.size() == 0 && b.size() == 0) return "0";
if (a.size() == 0)return b;
if (b.size() == 0)return a;
string ls, ss;
if (a.size() >= b.size()) {
ls = a; ss = b;
}
else {
ls = b; ss = a;
}
reverse(ls.begin(), ls.end());
reverse(ss.begin(), ss.end());
int carry = 0; int i = 0;
for (; i < ss.size(); i++) {
if (ls[i] - '0' + ss[i] - '0' + carry <= 9) {
ls[i] = (ls[i] - '0' + ss[i] - '0' + carry) + '0';
carry = 0;
}
else {
ls[i] = (ls[i] - '0' + ss[i] - '0' + carry) - 10 + '0';
carry = 1;
}
}
while (carry != 0) {
if (i == ls.size()) {
carry = 0;
ls += "1";
}
else {
if (ls[i] - '0' + carry <= 9) {
ls[i] = ls[i] + carry;
carry = 0;
}
else {
ls[i] = ls[i] + carry -10;
carry = 1;
}
}
i++;
}
reverse(ls.begin(), ls.end());
return ls;
}
//将a乘以b,结果用string返回
string strmul(string a, string b) {
if (a.size() == 0 || b.size() == 0)return "0";
string res = "";
for (int i = 0; i < b.size(); i++) {
if (b[i] == '0') {
//什么都不做
}
else {
for (int j = 0; j < b[i] - '0'; j++) {
res = stradd(res, a);
}
}
if (i != b.size() - 1)res += "0";
}
return res;
}
//将一个int转成字符串形式
string trans(int b) {
string res = "";
while (b != 0) {
res .insert( 0,1,(char)((b % 10) + '0'));
b /= 10;
}
return res;
}
//返回n的阶乘
string f(int n) {
string res = "1";
for (int i = 1; i <= n; i++) {
res = strmul(res, trans(i));
}
return res;
}
void test() {
string s1 = "81";
string s2 = "3";
cout << strmul(s1, s2) << endl;
int a = 9978023;
cout << trans(a) << endl;
}
int main() {
//test();
int N;
while (cin >> N) {
cout << f(N) << endl;
}
return 0;
}