求n累加和

#include <bits/stdc++.h>
using namespace std;
int a[100],n,l = 1;
void get_ans(){
    for (int i = 1;i <= 99;i++) //先给每个位上的数置0
        a[i] = 0;
    for (int i = 1;i <= n;i++) //从1 累加到 n
    {
        a[1] += i; //直接在个位上递增i
        for (int i = 1;i <= l;i++) //然后来处理进位问题 直接 + / 然后%一下就好
        {
            a[i+1] += (a[i]/10);
            a[i] = a[i] % 10;
        }
        while (a[l+1] > 0) //延长位数。用一个while和l就能搞定
        {
            l++;
            a[l+1] += (a[l] / 10);
            a[l] = a[l] % 10;
        }
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin >> n;
    get_ans();
    for (int i = l;i >= 1;i--)
       cout << a[i];
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xcfxcf/p/12563750.html