PAT 1069 The Black Hole of Numbers

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

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

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;


bool comp(char a,char b){
    return a>b;
}

int to_int(string s){
    int sum = 0;
    for(int i=0;i < s.size();i++){
        int num = s[i] - '0';
        sum = sum*10 + num;
    }
    return sum;
}


string minuss(string s1,string s2){
    string res;
    int a = to_int(s1);
    int b = to_int(s2);
    int c = a - b;
    res = to_string(c);
    int len = res.size();
    for(int i=0;i < (4-len);i++){ //加前导0;
        res = "0"+res;
    }
    return res;
}

int main(){

    string s;cin >> s;
    int len = s.size();
    for(int i=0;i < (4-len);i++){ //加前导0;
        s = "0"+s;
    }
    string s1 = s,s2 = s;
    sort(s1.begin(),s1.end(),comp);
    sort(s2.begin(),s2.end());
    string ans = minuss(s1,s2);
//    cout << ans;
    if(ans == "0000"){
        printf("%s - %s = %s\n",s1.c_str(),s2.c_str(),ans.c_str());
        return 0;
    }
    else{
        printf("%s - %s = %s\n",s1.c_str(),s2.c_str(),ans.c_str());
    }

    while(ans!="6174"){
        s1 = ans; s2 = ans;
        sort(s1.begin(),s1.end(),comp);
        sort(s2.begin(),s2.end());
        ans = minuss(s1,s2);
        printf("%s - %s = %s\n",s1.c_str(),s2.c_str(),ans.c_str());
    }

    return 0;
}

贼弱智,说是四位数,你给个0~10000范围,补前导0还算数字,服了

猜你喜欢

转载自www.cnblogs.com/cunyusup/p/10772040.html
今日推荐