本文主要是介绍【PAT】1069. The Black Hole of Numbers (20),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 – the “black hole” of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767, we’ll get:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
… …
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
翻译:对于除了4位数字一样的任意一个四位数字整数,如果我们降序排列这些数字,再升序排列这些数字,一个新的数字可以通过第一个数减第二个数来得到。重复此过程我们很快就会在数字6174—4位数字的“黑洞”停下。这个数字叫做Kaprekar常数。举个例子,从6767开始,我们将会得到:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
……
给你任意一个四位数字,你需要说明它进入黑洞的过程。
INPUT FORMAT
Each input file contains one test case which gives a positive integer N in the range (0, 10000).
翻译:每个输入文件包含一组测试数据,包括一个在(0,10000)范围内的正整数。
OUTPUT FORMAT
If all the 4 digits of N are the same, print in one line the equation “N - N = 0000”. Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.
翻译:如果所有4位数字都一样,则输出一行”N - N = 0000”。否则输出每一步计算结果直到它们的差为6174。所有数字必须按照四位数字输出。
Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000
解题思路
这道题注意一定要做一次循环,否则输入6174可能会没输出,还有每次将数字转换成数组时需要将数组清零。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
int N;
int a[4],b[4];
void transform(int x){int ccount=0;memset(a,0,sizeof(a));while(x){a[ccount++]=x%10;x/=10;}
}
int Num(int x[]){int sum=0;for(int i=3;i>=0;i--){sum=sum*10+x[i];}return sum;
}
int main(){ scanf("%d",&N);transform(N);while(1){sort(a,a+4);for(int i=0;i<4;i++)b[i]=a[3-i];int Max=Num(a);int Min=Num(b);int temp=Max-Min;printf("%04d - %04d = %04d\n",Max,Min,temp);if(temp==0||temp==6174)break;else transform(temp);}return 0;
}
这篇关于【PAT】1069. The Black Hole of Numbers (20)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!