HDU 1229 还是A+B

本文解析了一个典型的ACM竞赛题目——A+B问题,并提供了多种解题思路及代码实现,包括使用字符串处理的方法和数学运算的方法。

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1229

还是A+B

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20473    Accepted Submission(s): 9918


Problem Description
读入两个小于10000的正整数A和B,计算A+B。需要注意的是:如果A和B的末尾K(不超过8)位数字相同,请直接输出-1。
 

Input
测试输入包含若干测试用例,每个测试用例占一行,格式为"A B K",相邻两数字有一个空格间隔。当A和B同时为0时输入结束,相应的结果不要输出。
 

Output
对每个测试用例输出1行,即A+B的值或者是-1。
 

Sample Input
  
1 2 1 11 21 1 108 8 2 36 64 3 0 0 1
 

Sample Output
  
3 -1 -1 100
题解:题做多了,人也傻了,哎,看见这种就莫名其妙想到大数,所以我的第一次的代码是遍历做的,存到字符串里再比较,好傻啊

代码(警示后人):

#include<iostream>
using namespace std;
int main() {
	int a, b, k;
	char str1[9], str2[9];
	while (cin >> a >> b >> k && (a || b)) {
		int temp_a = a, temp_b = b, flag_a = 0, flag_b = 0;
			while (temp_a&&flag_a< k) {
				str1[flag_a++] = temp_a % 10 + 48;  /* 注意 +48  存成对应的字符  */
				temp_a /= 10;
			}
			while (flag_a < k)
				str1[flag_a++] = '0'; /* 注意 要带 单引号 */
			str1[flag_a] = '\0';
			while (temp_b&&flag_b < k) {
				str2[flag_b++] = temp_b % 10 + 48;
				temp_b /= 10;
			}
			while (flag_b < k)
				str2[flag_b++] = '0';
			str2[flag_b] = '\0';
			if (strcmp(str1, str2) == 0)
				cout << -1 << endl;
			else
				cout << a + b << endl;
	}
}
明明可以直接除以10的k次方取余就行:

#include<stdio.h>
#include <math.h>
int main()
{
	int a,b,c;
	while(scanf("%d%d%d",&a,&b,&c)==1,a!=0||b!=0)
	{
		int sum=pow(10,c);
		if(a%sum==b%sum)
			printf("-1\n");
		else
			printf("%d\n",a+b);
	}
	return 0;
}
或者遍历取余也行:

#include <stdio.h>
#include <string.h>
int main()
{
	int a,b,c,k;
	while(scanf("%d %d %d",&a,&b,&k)!=EOF)
	{
		if(a==0&&b==0) break;
		c=a+b;
		while(k>0)
		{
			if(a%10==b%10) k--;
			else break;
			a/=10;b/=10;
		}
		if(k==0) printf("-1\n");
		else printf("%d\n",c);
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值