PAT 乙级 (Basic Level) Practice (中文)1019
2019-02-03 17:31
375 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/arthur01p/article/details/86760272
1019 数字黑洞 (20 分)
给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的
6174,这个神奇的数字也叫 Kaprekar 常数。
例如,我们从
6767开始,将得到
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 61747641 - 1467 = 6174 ... ...
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。
输入格式:
输入给出一个 (0,10^4 ) 区间内的正整数 N。
输出格式:
如果 N 的 4 位数字全相等,则在一行内输出
N - N = 0000;否则将计算的每一步在一行内输出,直到
6174作为差出现,输出格式见样例。注意每个数字按
4位数格式输出。
输入样例 1:
6767
输出样例 1:
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174
输入样例 2:
2222
输出样例 2:
2222 - 2222 = 0000
代码
/*1.特殊输入6174时使用while语句进入不了循环 2.数字减法格式空格在哪儿加 3.不足四位数要用0补位*/ #include <cstdio> #include <algorithm> using namespace std ; int a, b ; //a, b 分别是非递增和非递减 void change (int x) { int str[4] ; str[0]=x/1000 ; //提取每一位数字 str[1]=x%1000/100 ; str[2]=x%100/10 ; str[3]=x%10 ; sort (str, str+4) ; //从小到大排序 a=str[3]*1000+str[2]*100+str[1]*10+str[0] ; b=str[0]*1000+str[1]*100+str[2]*10+str[3] ; } int main() { int n, c ; //c 为差值 scanf ("%d", &n) ; change (n) ; //直接得到a, b if ((n/1000==n%1000/100) && (n/1000==n%100/10) && (n/1000==n%10)) { printf ("%04d - %04d = 0000\n",n, n) ; return 0 ; //1111的整数倍时 } else { do { change(n) ; c=a-b ; printf ("%04d - %04d = %04d\n", a, b, c) ; n=c ; //将差值赋给n继续循环 } while (c!=6174) ; //若使用while循环则当6174的时候进入不了循环,而使用do...while...6174可以进入循环 } return 0 ; }
相关文章推荐
- PAT 乙级 (Basic Level) Practice (中文)1025
- PAT 乙级 (Basic Level) Practice (中文)1044
- PAT 乙级 (Basic Level) Practice (中文)1045
- PAT 乙级 (Basic Level) Practice (中文)1055
- PAT 乙级 (Basic Level) Practice (中文)1056
- PAT 乙级 (Basic Level) Practice (中文)1057
- PAT 乙级 (Basic Level) Practice (中文)1058
- PAT 乙级 (Basic Level) Practice (中文)1007
- PAT 乙级 (Basic Level) Practice (中文)1050
- PAT 乙级 (Basic Level) Practice (中文)1059
- PAT 乙级 (Basic Level) Practice (中文)1051
- PAT 乙级 (Basic Level) Practice (中文)1060
- PAT 乙级 (Basic Level) Practice (中文)1052
- PAT 乙级 (Basic Level) Practice (中文)1061
- PAT 乙级 (Basic Level) Practice (中文)1053
- PAT 乙级 (Basic Level) Practice (中文)1054
- PAT 乙级 (Basic Level) Practice (中文)1049
- PAT 乙级 (Basic Level) Practice (中文)1034
- PAT 乙级 (Basic Level) Practice (中文)1017
- PAT (Basic Level) Practice (中文)1070 结绳(C语言)