SDUT 2613 A+B 问题

This is an A+B Problem

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

As usual, there will be an A+B problem in warming up, this problem is:
Given two integers A and B, your job is to calculate the sum of A + B.

Input

 There are several test cases, For each test case:
There are two integers A, B for each case (0 ≤ A , B < 101000).

Output

 For each test case, output one line containing the result of A+B. 

Sample Input

1 2
11111111111 11111111111

Sample Output

3
22222222222

Hint

 

Source

 

解题思路:首先,这个题不是简单的a+b问题,注意题目中的条件(a和b最大到了十的1000次方),这个时候如果单纯的使用int等会越界。这个时候就应该考虑一下用字符,用字符存每一位数,然后再定义一个新的字符串,从最后一位开始,两个相加,如果大于十,先进一,然后本身减去十:如果小于十,直接存进去就行了。

代码如下:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char a[2000],b[2000],c[2000];//定义字符串
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));//对字符串清零
    int i,j,len1,len2,l,k;
    while(scanf("%s %s",a,b)!=EOF)
    {
        memset(c,0,sizeof(c));//对字符串c清零
        len1=strlen(a);
        len2=strlen(b);
        l=0;
        for(i=len1-1,j=len2-1; i>=0&&j>=0; i--,j--)
        {
            c[l++]=a[i]+b[j]-48;//先把每一位数上字符串两个相加的结果存进C字符串
        }
        if(i!=-1)
        {
        while(i>=0)
        {
            c[l++]=a[i--];
        }
        }
        if(j!=-1)
        {
        while(j>=0)
        {
            c[l++]=b[j--];
        }//这个是考虑到可能两个字符串的长度不一样
        }
        for(i=0; i<l; i++)
        {
            if(c[i]>=58)
            {
                c[i]=c[i]-10;
                c[i+1]=c[i+1]+1;
            }//满10进一
        }
        if(c[l]!=0)
        {
            printf("%c",c[l]+48);
        }//单独判断第一位,因为第一位可能有0的情况
        for(i=l-1; i>=0; i--)
        {
            printf("%c",c[i]);
        }
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值