原题链接: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;
}