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循環(huán)輸出,當滿足設定條件退出循環(huán)--> while(1){......break;}

? ? ? ? ? ?printf能夠格式化輸出-->printf("%0md",int)//輸出m位整形數據,不足時用0補全

易錯點:由于輸入的N范圍為(0,10000),所以對輸入的字符串要預處理,用0補齊四位


示例:

#include <iostream>

#include <string>

#include <algorithm>

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;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容