232056224hs @ 2024-03-24 19:43:21
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string add(const string& sum, const string& result) {
int carry = 0;
int len1 = sum.size();
int len2 = result.size();
int len = max(len1, len2);
for (int i = 0; i < len; ++i) {
int digit1 = i < len1 ? sum[len1 - 1 - i] - '0' : 0;
int digit2 = i < len2 ? result[len2 - 1 - i] - '0' : 0;
int sum = digit1 + digit2 + carry;
carry = sum / 10;
sum %= 10;
sum.push_back(sum + '0');
}
if (carry > 0) {
sum.push_back(carry + '0');
}
reverse(sum.begin(), sum.end());
return sum;
}
string multiply(const string& result, const string& num2) {
vector<int> result(result.size() + num2.size(), 0);
for (int i = result.size() - 1; i >= 0; --i) {
for (int j = num2.size() - 1; j >= 0; --j) {
int mul = (result[i] - '0') * (num2[j] - '0');
int p1 = i + j, p2 = i + j + 1;
result[p2] += mul;
result[p1] += result[p2] / 10;
result[p2] %= 10;
}
}
for (int i = result.size() - 1; i >= 0; --i) {
if (!result.empty() || result[i] != 0) {
result += to_string(result[i]);
}
}
return result.empty() ? "0" : result;
}
int main() {
int n; /*一个正整数 n*/
cin >> n;
// 初始化数据
string num1 = "1";
string num2 = "2";
string result = "1";
if (n > 1) {
for (int a = 0; a < n - 1; a++) {
// 计算乘积
string result = multiply(result, num2);
// 计算和
sum = add(sum, result);
// 更新num2的值
num2 = to_string(stoi(num2) + 1);
}
cout << sum ;
}
else {
cout << "1";
}
return 0;
}
by fp0cy1tz6mn4rd_ @ 2024-04-05 04:39:02
@232056224hs 是不是 stoi
越界了