HDU-1002 A + B Problem II Java大數

來源:互聯網
上載者:User

  一道最基本的大數相加題,java果然強大啊。

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        BigInteger a, b;        int T;        Scanner in = new Scanner(System.in);        T = in.nextInt();        for (int i = 1; i <= T; ++i) {            System.out.println("Case" + " " + i + ":");            a = in.nextBigInteger();            b = in.nextBigInteger();            if (i < T) {                System.out.println(a + " + " + b + " = " + a.add(b) );                System.out.println();            } else {                System.out.println(a + " + " + b + " = " + a.add(b));            }        }    }} 

  以下是以前寫的C++代碼:

#include<stdio.h>#include<stdlib.h>#include<math.h>#include<string.h>#define MAX 1000char a[MAX+1],b[MAX+1];int T;int main(){    scanf("%d",&T);    for(int w=1;w<=T;++w)    {        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        scanf("%s%s",a,b);        printf("Case %d:\n",w);        printf("%s + %s = ",a,b);        int len1=strlen(a);        int len2=strlen(b);        int fpla=MAX-( len1>len2 ? len1:len2);        for(int i=len1-1,k=MAX;i>=0;--i,--k)             a[k]=(a[i]-'0'),a[i]=0;                    for(int i=len2-1,k=MAX;i>=0;--i,--k)             b[k]=(b[i]-'0'),b[i]=0;                    for(int i=MAX;i>=fpla;--i)            a[i]+=b[i];         for(int i=MAX;i>=fpla;--i)        {            int c=a[i]/10;            a[i-1]+=c;            a[i]%=10;        }         for(int i=fpla+1;i<=MAX;++i)            printf("%d",a[i]);        puts("");        if(w<T)            puts("");    }    return 0;}

  對比之下,不解釋了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.