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:

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,+1.0E+4).

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:


Sample Input 2:

2222

Sample Output 2:


要点:1.字符串排序

           2.字符串补零

思路:先考虑特殊情况 当四位数字相同时 输出后直接退出-->升序==降序 即四位数字相同;

           利用while循环输出,当满足设定条件退出循环--> while(1){......break;}

           printf能够格式化输出-->printf("%0md",int)//输出m位整形数据,不足时用0补全

易错点:由于输入的N范围为(0,10000),所以对输入的字符串要预处理,用0补齐四位


示例:

#include

#include

#include

using namespace std;

void test()

{

    string str;

    cin >> str;

    while (1)

    {

        while (str.length() < 4)

            str.insert(0, "0");

        string str1 = str;

        sort(str1.begin(), str1.end());

        string str2 = str1;

        reverse(str2.begin(), str2.end());

        if (str2 == str1)

        {

            cout << str << " - " << str << " = 0000\n";

            return;

        }

        int num1 = stoi(str2);

        int num2 = stoi(str1);

        printf("%04d - %04d = %04d\n", num1, num2, num1 - num2);

        str = to_string(num1 - num2);

        if (num1 - num2 == 6174)

            break;

    }

}

int main()

{

    test();

    system("pause");

    return 0;

}

你可能感兴趣的:(PAT 甲级 1069 The Black Hole of Numbers (20分))