• 7月17日


    一:

    大整数相加问题

    A + B Problem II

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

    InputThe 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. 
    OutputFor 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

    2
    1 2
    112233445566778899 998877665544332211

    Sample Output

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

    分析:对于此题做法有两种:其一,使2字符串的中的字符数字减去'0',逐个相加大于等于10的可以使本位减10,下一位自增1,后面的处理就非常简单了;其二,便是读入字符串后先让各个字符减'0',一一对应存入整形数组中;之后再相加。对于2种方法大致是相同的,都要从后面向前加,逢十进位,以及数组初始化均要初始为0,一边方便运算。

    参考网址 http://blog.csdn.net/oosuifengoo/article/details/7089144


    源代码:

    #include <iostream>
    using namespace std;
    #include<stdio.h>
    #include<string.h>
    int main()
    {
    int n,m;
    scanf("%d",&n);
    m=1;
    while(m<=n)
    {
    char a[1000],b[1000];
    int i,c[1000]={0},la,lb,q;
    scanf("%s %s",a,b);
    la=strlen(a)-1;//计算给定字符串的(unsigned int型)长度,不包括''在内,返回s的长度,不包括结束符NULL。
    lb=strlen(b)-1;//ala,lb代表数组的长度
    q=la>lb?la:lb;//把字符长度长的赋给q
    for(i=0;la>=0;i++,la--)
    c[i]=a[la]-'0';
    for(i=0;lb>=0;lb--,i++)
    {
    c[i]+=b[lb]-'0';
    if(c[i]>=10)
    {
    c[i+1]++;
    c[i]-=10;
    }
    }
    printf("Case %d: ",m);
    printf("%s + %s = ",a,b);
    if(c[q+1]!=0)
    printf("%d",c[q+1]);//用于多出一位的情况如1+99
    for(q;q>=0;q--)
    printf("%d",c[q]);//从大位输到小位
    printf(" ");//格式
    if(m!=n)
    printf(" ");//格式
    m++;
    }
    return 0;
    }

  • 相关阅读:
    MSSQL·FOR XML PATH语法转义尖括号解决方案
    代码上传Github后乱码解决方案
    MSSQL·CONCAT函数的基础使用
    使用URL快捷方式提高效率
    数组逆序
    C++默认拷贝构造
    HO引擎近况20220512
    老猿谈谈对Tensorflow的理解
    学习笔记——Python中的IO问题理解
    PHP接口报错:Unable to init from given binary data
  • 原文地址:https://www.cnblogs.com/l-w-j/p/7197487.html
Copyright © 2020-2023  润新知