HDU 1753 大明A+B 高精度加法

import java.util.*;
import java.math.*;
public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        while(cin.hasNext()){
            BigDecimal a1 = new BigDecimal("0");
            BigDecimal a2 = new BigDecimal("0");
            a1 = cin.nextBigDecimal();
            a2 = cin.nextBigDecimal();
            System.out.println(a1.add(a2).stripTrailingZeros().toPlainString());
        }
    }
}


2017/5/11

用C++模拟了一发

#include <bits/stdc++.h>
using namespace std;

const int N = 500 + 10, INF = 0x3f3f3f3f;

void work(char *s, char *s1, char *s2) //整数部和小数部分离
{
    int k1 = 0, k2 = 0;
    bool flag = false;
    for(int i = 0; s[i]; i++)
    {
        if(s[i] == '.') flag = true;
        else
        {
            if(! flag) s1[k1++] = s[i];
            else s2[k2++] = s[i];
        }
    }
    s1[k1] = '\0', s2[k2] = '\0';
}
void add1(char *s1, char *s2, char *s3) //整数部分加法
{
    int len1 = strlen(s1), len2 = strlen(s2);
    reverse(s1, s1 + len1), reverse(s2, s2 + len2);
    int tm = 0, k = 0;
    for(int i = 0; i < len1 || i < len2; i++)
    {
        tm += i < len1 ? s1[i]-'0' : 0;
        tm += i < len2 ? s2[i]-'0' : 0;
        s3[k++] = tm % 10 + '0';
        tm /= 10;
    }
    if(tm) s3[k++] = tm + '0';
    s3[k] = '\0';
    reverse(s3, s3 + k);
}
bool add2(char *s1, char *s2, char *s3) //小数部分加法
{
    int len1 = strlen(s1), len2 = strlen(s2);
    int tm = 0;
    for(int i = max(len1, len2)-1; i >= 0; i--)
    {
        tm += i < len1 ? s1[i]-'0' : 0;
        tm += i < len2 ? s2[i]-'0' : 0;
        s3[i] = tm % 10 + '0';
        tm /= 10;
    }
    s3[max(len1,len2)] = '\0';
    return tm;
}
int main()
{
    char s1[N], s2[N];
    while(~ scanf("%s%s", s1, s2))
    {
        char t1[N], t2[N], t3[N], t4[N];
        work(s1, t1, t2);
        work(s2, t3, t4);
        char tm1[N], tm2[N];
        add1(t1, t3, tm1);
        bool f = add2(t2, t4, tm2);
        if(f) //小数部求和后进位了整数1,再进行一次整数加法
        {
            memcpy(t1, tm1, sizeof tm1);
            t2[0] = '1', t2[1] = '\0';
            add1(t1, t2, tm1);
        }
        int len = strlen(tm2);
        for(int i = len-1; i >= 0; i--) //消去小数部后缀0
        {
            if(tm2[i] == '0') tm2[i] = '\0';
            else break;
        }
        printf("%s", tm1);
        if(tm2[0] != '\0') printf(".%s", tm2);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值