1069. The Black Hole of Numbers<必看>

来源:互联网 发布:公司数据部门职责 编辑:程序博客网 时间:2024/06/11 09:57

题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1069


本题提供两种解法。一种是按数字处理,一种是按字符处理。

提示

1. 题目说0<n<10000,这就意味着,输入小于4位的数,需要补全到4位再处理。

2. 本题中最隐藏的一个点:6174,为输入数据时,至少需要输出一次。 因此,至少执行一次减法。应该使用do-while。

3. 对于补全4位,2中方法各有不同,具体见代码。

4. atoi是库函数,但itoa不是库函数,不可使用。

5. 使用sprintf实现int到char[], 的转换。

按字符实现

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;bool cmp(char a, char b){return a>b;}int main(){char a[5], b[5], n[5];scanf("%s", n);int len = strlen(n);int dis = 4-len;// dis大于0时,会进行补全memset(a, '0', sizeof(a));int i=len-1;while(i>=0){a[i+dis] = n[i];i--;}a[4]=0;do{sort(a, a+4, cmp);strcpy(b, a);int i=0, j=3;while(i<j){char t = b[i];b[i] = b[j];b[j] = t;i++, j--;}printf("%s - %s = ", a, b);if(strcmp(a,b) == 0){printf("0000\n");break;}for(i=3; i>=0; i--){a[i] -= b[i];/*-------------------------  这一步,很关键  a[i] += '0';  -----------------------*/a[i] += '0';if(a[i] < '0'){a[i-1]--;a[i] = a[i] + 10;}}printf("%s\n", a);}while(strcmp(a, "6174") != 0);return 0;}

按数字实现

#include <stdio.h>#include <stdlib.h>#include <algorithm>using namespace std;bool cmp(char x, char y){return x>y;}int main(){int n;char s[5];scanf("%d", &n);do{int i;for(i=3; i>=0; i--){s[i] = n%10 +'0';n /= 10;}//得到4位数字的字符形式s[4]=0;sort(s, s+4, cmp);int a = atoi(s);sort(s, s+4);int b = atoi(s);n = a-b;printf("%04d - %04d = %04d\n", a, b, n);}while(n !=6174 && n != 0);return 0;}

代码3

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <algorithm>using namespace std;bool cmp(char a, char b){return a > b;}int main(){int a;// a = a - b // a == 6174 or a == 0stopscanf("%d", &a);do{char sa[10], sb[10];sprintf(sa, "%04d", a);sprintf(sb, "%04d", a);sort(sa, sa+4, cmp);sort(sb, sb+4);a = atoi(sa);int b = atoi(sb);printf("%04d - %04d = ", a, b);a = a-b;printf("%04d\n", a);}while(a != 6174 && a != 0);return 0;}



0 0
原创粉丝点击