- 题目描述:
-
12翻一下是21,34翻一下是43,12+34是46,46翻一下是64,现在又任意两个正整数,问他们两个数反转的和是否等于两个数的和的反转。
- 输入:
-
第一行一个正整数表示测试数据的个数n。
只有n行,每行两个正整数a和b(0<a,b<=10000)。
- 输出:
-
如果满足题目的要求输出a+b的值,否则输出NO。
- 样例输入:
-
2 12 34 99 1
- 样例输出:
-
46 NO
思路:
数字反转可借助字符串来实现。(见代码1)
更好的办法是直接反转。(见代码2)
代码1:
#include <stdio.h> #include <string.h> #define MAX 7 void fanzhuan(char *a, char *af) { int i; int len = strlen(a); for (i=0; i<len; i++) af[i] = a[len-1-i]; for (i=len-1; i>=0; i--) { if (af[i] > '0') { af[i+1] = ' '; break; } } } void add(char *a, char *b, char *sum) { int lena=strlen(a), lenb=strlen(b); int i; char tmp; for (i=0; i<lena/2; i++) { tmp = a[i]; a[i] = a[lena-1-i]; a[lena-1-i] = tmp; } for (i=0; i<lenb/2; i++) { tmp = b[i]; b[i] = b[lenb-1-i]; b[lenb-1-i] = tmp; } for (i=lena; i<MAX; i++) a[i] = '0'; for (i=lenb; i<MAX; i++) b[i] = '0'; for (i=0; i<MAX; i++) sum[i] = '0'; /* for (i=0; i<MAX; i++) printf("%c", a[i]); printf(" "); for (i=0; i<MAX; i++) printf("%c", b[i]); printf(" "); //printf("a[0] = %c ", a[0]); //printf("b[0] = %c ", b[0]); //printf("sum[0] = %c ", sum[0]); */ for (i=0; i<MAX-1; i++) { sum[i] += a[i] - 48 + b[i] - 48; //printf("a[i] = %c ", a[i]); //printf("b[i] = %c ", b[i]); //printf("sum[i] = %c ", sum[i]); if (sum[i] > '9') { sum[i+1] = ((sum[i]-48)/10) + 48; sum[i] = ((sum[i]-48)%10) + 48; } } //for (i=0; i<MAX; i++) // printf("%c", sum[i]); //printf(" "); for (i=MAX-1; i>=0; i--) { if (sum[i] > '0') { sum[i+1] = ' '; break; } } if (i < 0) sum[1] = ' '; int lens = strlen(sum); for (i=0; i<lens/2; i++) { tmp = sum[i]; sum[i] = sum[lens-1-i]; sum[lens-1-i] = tmp; } } int main(void) { char a[10000][MAX], b[10000][MAX]; char af[MAX], bf[MAX], sum[MAX], sumf[MAX], fsum[MAX]; int n; int i; while (scanf("%d", &n) != EOF) { for (i=0; i<n; i++) scanf("%s%s", a[i], b[i]); for (i=0; i<n; i++) { fanzhuan(a[i], af); //printf("af = %s ", af); fanzhuan(b[i], bf); //printf("bf = %s ", bf); add(a[i], b[i], sum); //printf("sum = %s ", sum); fanzhuan(sum, sumf); //printf("sumf = %s ", sumf); add(af, bf, fsum); //printf("fsum = %s ", fsum); if (strcmp(fsum, sumf) == 0) printf("%s ", sum); else printf("NO "); } } return 0; } /************************************************************** Problem: 1089 User: liangrx06 Language: C Result: Accepted Time:0 ms Memory:976 kb ****************************************************************/
代码2:
#include <stdio.h> #include <string.h> int fz(int a) { int n = 0; while (a) { n = n*10 + a%10; a /= 10; } return n; } int main(void) { int n, i; int a, b; scanf("%d", &n); for (i=0; i<n; i++) { scanf("%d%d", &a, &b); if (fz(a)+fz(b) == fz(a+b)) printf("%d ", a+b); else printf("NO "); } return 0; } /************************************************************** Problem: 1089 User: liangrx06 Language: C++ Result: Accepted Time:0 ms Memory:1020 kb ****************************************************************/