1510 - 还是A+B
时间限制 : 1 秒
内存限制 : 32 MB
读入两个小于10000的正整数A和B,计算A+B。需要注意的是:如果A和B的末尾K(不超过8)位数字相同,请直接输出-1。
题目输入
测试输入包含若干测试用例,每个测试用例占一行,格式为"A B K",相邻两数字有一个空格间隔。当A和B同时为0时输入结束,相应的结果不要输出。
题目输出
对每个测试用例输出1行,即A+B的值或者是-1。
输入/输出样例
输入格式
2 3 1 12 22 1 11 111 2 0 0 2
输出格式
5 -1 -1
C语言解答
int main (void) { int a, b, k; int l; //除数 while (1) { /*处理一行*/ a = b = k = 0; l = 1; scanf("%d%d%d", &a, &b, &k); for (;k > 0; --k) { l *= 10; } if (a == 0 && b == 0)break; if ( a % l == b % l ) printf("-1\n"); else printf("%d\n", a+b); } return 0; }
C++解答
#include<stdio.h> #include<math.h> int main() { int a,b,k,i,m,t; while(scanf("%d%d%d",&a,&b,&k)!=EOF,a||b) { if(a==b) printf("-1\n"); else { m=fabs(a-b); t=0; i=10; while(1) { if(m%i==0) t++; else break; i*=10; } printf(t>=k?"-1\n":"%d\n",a+b); } } return 0; }
Java解答
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int A=sc.nextInt(),B=sc.nextInt(),K=sc.nextInt(); if(A==0&&B==0){ break; } int n=1; while(K-->0){ n*=10; } int output=A%n==B%n ? -1:A+B; System.out.println(output); } sc.close(); } }
Python解答
while True: a, b, c = [int(i) for i in raw_input().split()] if b == 0 and a == 0: break if abs(a - b) % (10 ** c) == 0: print(-1) else: print(a + b)