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.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0,104).
Output Specification:
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.
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
代码长度限制
16 KB
时间限制
200 ms
内存限制
64 MB
C++ (g++)
#include <bits/stdc++.h>
using namespace std;
bool cmp1(char a, char b) {
return a > b;
}
bool cmp2(char a, char b) {
return a < b;
}
//高精度减法
//保证a>b;
string diff(string a, string b) {
vector<int> A, B, C;
for (int i = a.size() - 1; i >= 0; i--) A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i--) B.push_back(b[i] - '0');
int t = 0;
for (int i = 0; i < A.size(); i++) {
t += A[i];
if (i < B.size()) t -= B[i];
C.push_back((t + 10) % 10);
if (t < 0) t = -1;
else t = 0;
}
string c;
//if(C.size()>1&&C.back()==0) C.pop_back();
for (int i = C.size() - 1; i >= 0; i--) c += to_string(C[i]);
return c;
}
int main() {
char n[5]={'0','0','0','0'};
int k;
scanf("%d",&k);
string bb = to_string(k);
int i=3,j=bb.size()-1;
while(j>=0&&i>=0){
n[i--]=bb[j--];
}
string last = "";
int l = strlen(n);
while (1) {
char m1[5], m2[5];
strcpy(m1, n);
strcpy(m2, n);
sort(m1, m1 + l, cmp1);
sort(m2, m2 + l, cmp2);
string a1 = m1;
string a2 = m2;
string s = diff(a1, a2);
if (s == last) break;
cout << a1 << " - " << a2 << " = " << s << endl;
last = s;
strcpy(n, s.c_str());
}
return 0;
}