《ACM 书中题目》 N

  • 题目

    The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.
    Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.
    ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

  • 理解思路
    输入一对数据,分别把两数到过来再相加,最后再把结果倒过来。

    把一个数倒过来由调用函数实现,减少代码量,要注意倒序过程中首位为零的情况。

  • AC代码

#include<bits/stdc++.h>
using namespace std;
int rev(int x)
{
    int result = 0;
    int reminder;
    int negative = 1;
    if(x<0)
    {
        x=-x;
        negative=-1;
    }
    while(x%10>=0&&x>0)
    {
        reminder=x%10;
        result=result*10+reminder;
        x=(int)x/10;
    }
    result*=negative;
    return result;
}
int main()
{
    int i,j,k,n,m;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>j;
        cin>>k;
        m=rev(rev(j)+rev(k));
        cout<<m<<endl;
    }
}
  • 总结
    刚开始在被调函数内使用pow()函数
for(i=0;i<s.size();i++)
    {
        sum+=s[i]*pow(10,j-1);
        j--;
    }
发现因为对pow()函数的参数把握不准出现奇数位数字倒序后总是比实际结果少1的情况,于是改用AC代码中的方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值