九度OJ 1089:数字反转 (数字反转)
- 题目描述:
-
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] = '\0'; 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("\n"); for (i=0; i<MAX; i++) printf("%c", b[i]); printf("\n"); //printf("a[0] = %c\n", a[0]); //printf("b[0] = %c\n", b[0]); //printf("sum[0] = %c\n", sum[0]); */ for (i=0; i<MAX-1; i++) { sum[i] += a[i] - 48 + b[i] - 48; //printf("a[i] = %c\n", a[i]); //printf("b[i] = %c\n", b[i]); //printf("sum[i] = %c\n", 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("\n"); for (i=MAX-1; i>=0; i--) { if (sum[i] > '0') { sum[i+1] = '\0'; break; } } if (i < 0) sum[1] = '\0'; 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\n", af); fanzhuan(b[i], bf); //printf("bf = %s\n", bf); add(a[i], b[i], sum); //printf("sum = %s\n", sum); fanzhuan(sum, sumf); //printf("sumf = %s\n", sumf); add(af, bf, fsum); //printf("fsum = %s\n", fsum); if (strcmp(fsum, sumf) == 0) printf("%s\n", sum); else printf("NO\n"); } } 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\n", a+b); else printf("NO\n"); } return 0; } /************************************************************** Problem: 1089 User: liangrx06 Language: C++ Result: Accepted Time:0 ms Memory:1020 kb ****************************************************************/
编程算法爱好者。