UVA10035Primary Arithmetic


Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which a 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.
Input

Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.
Output

For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.
Sample Input

123 456
555 555
123 594
0 0
Sample Output

No carry operation.
3 carry operations.
1 carry operation.
解题思路:这道题不难,但是不难的题陷阱很多(好吧,我确实很水...)首先,高精度的大数相加,只是使用思想,不比做成那样,大可使用Int
把进位数记下统计即可。以防万一,我用了string(据说可以容纳1个G的数据,待考证),从屁股开始,对数相加,carryset就是进位数的统计了。
得懂大数相加会觉得这题很简单(好吧,我没学好),说白了,就是小学加法的竖式,模拟一下即可。
接下来说一下陷阱吧,首先单复数,输出为负数时,单词应该是operations,对,有一个s;
其次,例如999+1这样的数,你得记得把进位数向前加;
再者,例如989+1这样的数,8+1,不须进位,所以要把进位清零。
我的方法可能弱爆了,欢迎前来切磋~~感激不禁!
提供几个坑爹的测试数据:
input:
989 1
1 989
11 0
0 11
2 3
2234 766
0 0

output:
1 carry operation.
1 carry operation.
No carry operation.
No carry operation.
No carry operation.
3 carry operations.

#include <iostream>
#include <string>
using namespace std;


#include <iostream>
#include <stdio.h>
using namespace std;


int main()
{
	string num1;
	string num2;

	while (cin >> num1 >> num2)
	{
		if (num1 == "0" && num2 == "0")
		{
			break;
		}
		int count = 0;
		int carryset = 0;
		int i = num1.length() - 1;
		int j = num2.length() - 1;

		for (; i >= 0 && j >= 0;)
		{
			if ((num1[i] - '0' + num2[j] - '0' + carryset) >= 10)
			{
				count += 1;
				carryset = 1;
			}
			else
			{
				carryset = 0;
			}
			i--;
			j--;
		}

		while (i>=0 && (num1[i] - '0' <= 9 && num1[i] - '0'>0))
		{
			if ((num1[i] - '0' + carryset) >= 10)
			{
				count += 1;
				carryset = 1;
			}
			else
			{
				carryset = 0;
			}
			i--;
		}

		while (j>=0 && (num2[j] - '0' <= 9 && num2[j] - '0'>0))
		{
			if ((num2[j] - '0' + carryset) >= 10)
			{
				count += 1;
				carryset = 1;
			}
			else
			{
				carryset=0;
			}
			j--;
		}

		if (count == 0)
		{
			cout << "No carry operation." << endl;
		}
		else if (count == 1)
		{
			cout << count << " carry operation." << endl;
		}
		else
		{
			cout << count << " carry operations." << endl;
		}
	}
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值