HDOJ 1002 高精度加法

来源:互联网 发布:apache安装包下载 编辑:程序博客网 时间:2024/05/16 08:21

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 290083    Accepted Submission(s): 55742


Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

Sample Input
21 2112233445566778899 998877665544332211
 

Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110

//

//  main.cpp

//  1003

//

//  Created by 张嘉韬 on 16/1/8.

//  Copyright © 2016 张嘉韬. All rights reserved.

//

#include <iostream>

#include <cstring>

using namespace std;

int main(int argc, const char * argv[]) {

    //freopen("/Users/zhangjiatao/Desktop/input.txt","r",stdin);

    char a1[2000],b1[2000];

    int a[2000],b[2000],c[2000],lena,lenb,lenc,temp;

    int n;

    cin>>n;

    for(int t=1;t<=n;t++)

    {

        memset(a,0,sizeof(a));

        memset(b,0,sizeof(b));

        memset(c,0,sizeof(c));

        cin>>a1>>b1;

        lena=strlen(a1);

        lenb=strlen(b1);

        for(int i=0;i<lena;i++) a[lena-i]=a1[i]-48;

        for(int i=0;i<lenb;i++) b[lenb-i]=b1[i]-48;

        lenc=1;

        while(lenc<=lena||lenc<=lenb)

        {

            temp=a[lenc]+b[lenc]+c[lenc];

            if(temp>=10) c[lenc]=temp-10,c[lenc+1]++;

            else  c[lenc]=temp;

            lenc++;

        }

        if(c[lenc]==0) lenc--;

        cout<<"Case "<<t<<":"<<endl;

        //cout<<lena<<" "<<lenb<<endl;

        for(int i=lena;i>=1;i--) cout<<a[i];

        cout<<" + ";

        for(int i=lenb;i>=1;i--) cout<<b[i];

        cout<<" = ";

        for(int i=lenc;i>=1;i--) cout<<c[i];

        cout<<endl;

        if(t!=n) cout<<endl;

    }

    return 0;

}

总结:
1.当题目解决后应该及时的进行总结,如果一段时间之后再总结,当时的一些重要的经验和教训很难被积累下来,这样的话效率比较低。
2.可以用字符串来储存特别大的正数,输入方法也很简单直接用cin就行,获取长度用strlen,注意这些方法都试使用字符数组的时候用的,如果要使用string的话,获取长度要用name.size()或name.length()(两个函数在功能上没有区别)
0 0
原创粉丝点击