CodeVS 3116 高精度练习之加法

题目大意:

http://codevs.cn/problem/3116/

题解:

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#define trans(x)(x-'0')

using namespace std;

string trans2(int i)
{
    stringstream s;
    s << i;
    string ss;
    s >> ss;
    return ss;
}

int main()
{
    string s1,s2;
    cin >> s1 >> s2;
    int l1 = s1.length();
    int l2 = s2.length();
    if(l1 < l2){
        string tmp = s2;
        s2 = s1;
        s1 = tmp;
    }
    l1 = s1.length();
    l2 = s2.length();
    string str;

    int flag = 0;
    int j = l1-1;

    for(int i = l2-1; i >= 0; i--,j--)
    {
        if(trans(s2[i])+trans(s1[j]) >= 10)
        {
            int result = (trans((s2[i])+trans(s1[j]))) % 10 + flag;
            flag = 1;
            str.insert(0,trans2(result));
        }

        else if(trans(s2[i])+trans(s1[j]) + flag >= 10)
        {
            int result = 0;
            flag = 1;
            str.insert(0,trans2(result));

        }

        else
        {
            int result = trans((s2[i])+trans(s1[j])) + flag;
            flag = 0;
            str.insert(0,trans2(result));
        }
    }

    for(int i = j; i >= 0; i-- )
    {
        if(trans(s1[i])+flag >= 10)
        {
            int result = (trans(s1[i])+flag) % 10;
            flag = 1;
            str.insert(0,trans2(result));
        }
       else
       {
           int result = (trans(s1[i])+flag);
           flag = 0;
           str.insert(0,trans2(result));
       }
    }

    if(flag == 1)
        str = '1' + str;

    cout << str << endl;


    return 0;
}

 之前写的太麻烦,给个新的:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>

using namespace std;

char a[501];
char b[501];
int res[501];

int add(char a[], char b[])
{
    int la = strlen(a) - 1;
    int lb = strlen(b) - 1;

    int tmp = 0;
    int flag = 0;
    while(la >= 0)
    {
        int aa =  a[la] - '0';
        int bb = (lb >= 0)? b[lb] - '0' : 0;

        res[tmp++] = (aa + bb + flag) < 10 ? aa+bb+flag : (aa+bb+flag)%10;
        flag = (aa + bb + flag) / 10;

        la--;
        lb--;

    }

    if(flag == 1){
        res[tmp++] = 1;
    }

    return tmp;


}
int main()
{
    cin >> a >> b;
    int la = strlen(a);
    int lb = strlen(b);
    int count = 0;
    if(la > lb)
        count = add(a,b);
    else
        count = add(b,a);

    for(int i = count-1; i >= 0; i--)
        cout << res[i];
    cout << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/zyqBlog/p/7603576.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值