复习C/C++编程之大数相加

来源:互联网 发布:gk5原厂轮毂数据 编辑:程序博客网 时间:2024/05/12 11:29


两个数相加一直是C/C++最基础的问题,一般性的解法都是定义两个int型变量,然后输出两数相加的结果即可。可是众所周知,int型变量都有它的取值范围。对于不同系统不同编译环境,可能有所不同,比如16位系统,int只占两个字节,即16位,因此能表示的整数值的范围是2^16,而32位、64位系统又不一样。总而言之它总是有一个范围,当我们需要计算大数相加时,这个大数超过了int型变量的范围时,我们需要存为字符数组或者字符串,一位位进行操作。

大数相加——杭电OJ(1002)

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

AC代码:

#include <iostream>#include <string>using namespace std;int main(){    int T;    string s1,s2;    char sum[1001];    cin>>T;    int len1,len2;    for(int i=1;i<=T;i++)    {            cin>>s1>>s2;        len1 = s1.size();len2 = s2.size();        cout<<"Case "<<i<<":"<<endl            <<s1<<" + "<<s2<<" = ";        int len = 0;        int p = 0;        for(; len1 > 0 || len2 > 0; len1--, len2--)        {            if(len1>0&&len2>0){            sum[len] = (((s1[len1-1]-'0')+(s2[len2-1]-'0')+p)%10)+'0';                p = ((s1[len1-1]-'0')+(s2[len2-1]-'0')+p)/10;            }            else if(len1<=0)            {                sum[len] = (((s2[len2-1]-'0')+p)%10)+'0';                p = ((s2[len2-1]-'0')+p)/10;            }            else            {                sum[len] = (((s1[len1-1]-'0')+p)%10)+'0';                p = ((s1[len1-1]-'0')+p)/10;            }            len++;        }        if(p>0)            cout<<'1';        for(int k = len-1;k>=0;k--)            cout<<sum[k];        cout<<endl;        if(i!=T)           cout<<endl;    }    return 0;}
代码解释:

用s1和s2两个字符串去存储输入的数字,然后从最后一位开始进行位与位的相加,保留进位p。每完成一位的加法,计算的位置就往前移一位,即循环中的len1--和len2--。不过每次计算之前都先判断是否其中一个数字已经被计算完,因为两数字不一定位数相同,如果s1已经计算完,只需要计算s2与进位p的和即可,反之亦然。值得注意的是:循环结束后并没有结束,有可能最后一次计算产生了进位,因此我们还需要判断p是否大于0,如果大于0,那先输出第一位“1”,然后倒序输出存放结果的数组,因为循环计算的时候,根据加法规则是从最后一位开始计算的,计算结果存放在了数组的第一位。



坚持比什么都重要

1 0