1069 The Black Hole of Numbers

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 holeof 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 (.

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

/*
    Name:
    Copyright:
    Author:  流照君
    Date: 2019/8/17 16:21:24
    Description:
*/
#include <iostream>
#include<string>
#include <algorithm>
#include <vector>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
string s;
ll to_digit1(string ss)
{
	ll n=ss.size();
	ll sum=0;
	for(int i=0;i<n;i++)
	{
		sum=sum*10+(ss[i]-'0');
	}
	return sum;
}

string to_string1 (ll sum1)
{
	string ss;
	while(sum1>0)
	{
		ll dig=sum1%10;
		sum1=sum1/10;
		ss=char(dig)+ss;
	}
	return ss;
}
bool cmp1(char x,char y)
{
	return x<y;
}
bool cmp2(char x,char y)
{
	return x>y;
}
int main(int argc, char** argv)
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    string s1,s2;
    cin>>s;
    s.insert(0, 4 - s.length(), '0');
    s1=s;
    s2=s;
    sort(s1.begin() ,s1.end(),cmp1);
    sort(s2.begin() ,s2.end(),cmp2);
    if(s1==s2)
    cout<<s2<<" - "<<s1<<" = "<<"0000"<<endl;
    else
    {
    	//ll ce=to_digit1("7856");
    	//cout<<ce<<endl;
        //cout<<s2<<" - "<<s1<<" = "<<"0000"<<endl;
    	//exit(0);
    	do
    	{
    		int d1=stoi(s1);
    		int d2=stoi(s2);
    		int d3=d2-d1;
    		printf("%04d - %04d = %04d\n",d2,d1,d3);
    		//cout<<d2<<" - "<<d1<<" = "<<d3<<endl;
    		s=to_string(d3);
    		s.insert(0, 4 - s.length(), '0'); //the key
    		s1=s;
    		s2=s;
    		sort(s1.begin() ,s1.end(),cmp1);
    		sort(s2.begin() ,s2.end(),cmp2);
		}while(s!="6174");
	}
    return 0;
}

  

posted @ 2019-08-17 17:26  流照君  阅读(7475)  评论(0编辑  收藏  举报