题目描述
读入两个小于 10000 的正整数 A 和 B,计算 A+B。需要注意的是:如果 A 和 B 的末尾 K(不 超过 8)位数字相同,请直接输出-1。
输入: 测试输入包含若干测试用例,每个测试用例占一行,格式为"ABK",相邻两数字有一个空格 间隔。当 A 和 B 同时为 0 时输入结束,相应的结果不要输出。
输出: 对每个测试用例输出 1 行,即 A+B 的值或者是-1。
样例输入:
1 2 1
11 21 1
108 8 2
36 64 3
0 0 1
样例输出:
3
-1
-1
100
解题思路
#include<iostream>
using namespace std;
int main()
{
int a,b,k;
while(cin>>a>>b>>k){
if(a==0&&b==0)
{
break;
}
int c=a,d=b;
bool flag=true;
for(int i=0;i<k;i++)
{
if(c%10==d%10){
c=(c-c%10)/10;//逐步取出数字
d=(d-d%10)/10;
}else{
flag=false;
break;
}
}
if(flag==false){
cout<<a+b<<endl;
}else{
cout<<"-1"<<endl;
}
}
return 0;
}