1280.就问你慌不慌 SDNUOJ 1280

Description
求N进制的高精度加法
Input
第一行输入N(2≤N≤10)

第二行两个数X Y(长度均≤100)

Output
输出N进制下X和Y的和
Sample Input
5
2 4
Sample Output
11

高精度加法

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    while(cin >> n)
    {
        char a[105] = {}, b[105] = {}, c[105] = {};
        cin >> a >> b;
        int lena = strlen(a);
        int lenb = strlen(b);
        ///确保 a 是较大(较长)的数字
        if(lena < lenb)
        {
            for(int i = 0; i < lenb; i++)
            {
                swap(a[i], b[i]);
            }
            swap(lena, lenb);
        }
        reverse(a, a + lena);
        reverse(b, b + lenb);
//    cout << a << '\n' << b << '\n';
        ///逢十所进
        int j = 0;
        int i;
        for(i = 0; i < lenb; i++)
        {
            c[i] = (a[i] + b [i] - '0' - '0' + j) % n + '0';
            j = (a[i] + b[i] - '0' - '0' + j) / n;
        }
        for(int k = i; k < lena; k++)
        {
            ///照顾衔接处及末(反转后)
            c[k] = (a[k] + j - '0' ) % n + '0';
            j = (a[k] + j - '0' ) / n;
        }
        if(j != 0)
            cout << j;
        for(int m = lena - 1; m >= 0; m--)
            cout << c[m];
        cout << '\n';
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhaobaole2018/article/details/85370535