关键在于字符串的加法
#include <iostream> #include <string> #include "vector" using namespace std; string multiply(char a, int n) {//构造n个a的字符串 string ans; for (int i = 0; i < n; i++) { ans = a + ans; } return ans; } string add(string a, string b) { //首先将两个字符串对齐 int commonSize = a.size() > b.size() ? a.size() : b.size(); if (a.size() > b.size()) { for (int i = 0; i < commonSize - b.size(); i++) b = '0' + b; } else { for (int i = 0; i < commonSize - a.size(); i++) a = '0' + a; } //从低位开始进行带进位相加,取模,进位,结果存入a中 int carry = 0; for (int i = commonSize - 1; i >= 0; i--) { int temp = a[i] - '0' + b[i] - '0' + carry; a[i] = temp % 10 + '0'; carry = temp / 10; } if (carry != 0) a = '1' + a; return a; } int main() { char a; int n; while (cin >> a >> n) { // 注意 while 处理多个 case string ans = "0"; for (int i = 1; i <= n; i++) { ans = add(ans, multiply( a, i)); } cout << ans << endl; } } // 64 位输出请用 printf("%lld")