10

poj 1503 高精度加法

 2 years ago
source link: https://zxs.io/article/179
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

poj 1503 高精度加法

2013-09-07 分类:未分类 阅读(4401) 评论(0)

把输入的数加起来,输入0表示结束。

先看我Java代码,用BigINteger类很多东西都不需要考虑,比如前导0什么的,很方便。不过java效率低点,平均用时600ms,C/C++可以0ms过。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        BigInteger sum = BigInteger.valueOf(0);
        BigInteger a;
        a = cin.nextBigInteger();
        while (true) {
            sum = sum.add(a);
            if (a.compareTo(BigInteger.valueOf(0)) == 0)
                break;
            a = cin.nextBigInteger();
        }
        System.out.println(sum);
        cin.close();
    }
}

下面是我从网上找的C++代码,无外乎就是用数组模拟实现大数的加法。

#include<stdio.h>
#include<string.h>

#define N 20000

int ans[N],f,max;

void hadd(char a[])
{
    f=0;
    int n=strlen(a);
    for(int i=n-1;i>=0;i--)
    {
        a[i]-='0';
        ans[f]+=a[i];
        ans[f+1]+=ans[f]/10;
        ans[f]%=10;
        f++;
        if(max<f) max=f;
    }
}

int main()
{
    memset(ans,0,sizeof(ans));
    while(1)
    {
        char s[N];
        scanf("%s",s);
        if(strlen(s)==1&&s[0]=='0') break;
        hadd(s);
    }
    int flag=0;
    for(int i=N-1;i>=0;i--)
    {
        if((!flag&&ans[i]!=0)||flag||(!flag&&i==0))
        {printf("%d",ans[i]);flag|=1;}
    }
    puts("");
    return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK