PAT 乙級 1019.數字黑洞 C++/Java

題目來源html

給定任一個各位數字不徹底相同的 4 位正整數,若是咱們先把 4 個數字按非遞增排序,再按非遞減排序,而後用第 1 個數字減第 2 個數字,將獲得一個新的數字。一直重複這樣作,咱們很快會停在有「數字黑洞」之稱的 6174,這個神奇的數字也叫 Kaprekar 常數。ios

例如,咱們從6767開始,將獲得spa

7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174 7641 - 1467 = 6174 ... ... 

現給定任意 4 位正整數,請編寫程序演示到達黑洞的過程。code

輸入格式:

輸入給出一個 ( 區間內的正整數 N。htm

輸出格式:

若是 N 的 4 位數字全相等,則在一行內輸出 N - N = 0000;不然將計算的每一步在一行內輸出,直到 6174 做爲差出現,輸出格式見樣例。注意每一個數字按 4 位數格式輸出。blog

輸入樣例 1:

6767

輸出樣例 1:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

輸入樣例 2:

2222

輸出樣例 2:



2222 - 2222 = 0000

思路1:

用string接收輸入,當數字不足四位數的時候,用0補高位排序

將字符串數字從高到低排序,再從低到高排序,分別轉換成整型數字ip

獲得的差值再轉換成字符串,不足四位數高位補0,知足條件則退出循環。ci

須要注意的是,當差值爲6174或者0000的時候要結束循環,當輸入爲6174的時候也要進行計算,因此這裏用do while。字符串

思路2:

用int接收輸入,和思路1差很少,將輸入轉化成字符串,補0

而後作兩次排序,轉成整形數字再相減,獲得差值

最用用%4d佔位符,輸出整形數字便可

 

C++實現:

思路1

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <vector>
 5 #include <map>
 6 #include <set>
 7 #include <string>
 8 #include <cctype>
 9 #include <unordered_map>
10 using namespace std;
11 
12 bool cmp(char a, char b)
13 {
14     return a > b;    //從高到低排序
15 }
16 
17 int main()
18 {
19     int result = 0;
20     string N;
21     cin >> N;
22     N.insert(0, 4 - N.size(), '0');
23     do 
24     {
25         string a = N;
26         string b = N;
27         sort(a.begin(), a.end(), cmp);
28         sort(b.begin(), b.end());
29         result = stoi(a) - stoi(b);
30         N = to_string(result);
31         N.insert(0, 4 - N.size(), '0');
32         cout << a << " - " << b << " = " << N << endl;
33     } while (N != "6174" && N != "0000");
34     return 0;
35 }

思路2

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <vector>
 5 #include <map>
 6 #include <set>
 7 #include <string>
 8 #include <cctype>
 9 #include <unordered_map>
10 using namespace std;
11 
12 bool cmp(char a, char b)
13 {
14     return a > b;
15 }
16 
17 int main()
18 {
19     int N;
20     int result = 0;
21     cin >> N;
22     string s = to_string(N);
23     do 
24     {
25         s.insert(0, 4 - s.size(), '0');
26         sort(s.begin(), s.end(), cmp);
27         int a = stoi(s);
28         sort(s.begin(), s.end());
29         int b = stoi(s);
30         result = a - b;
31         printf("%04d - %04d = %04d\n",a,b,result);
32         s = to_string(result);
33     } while (result != 0 && result != 6174);
34 
35     return 0;
36 }

 

 

 

Java實現:

 

 

 

小結:

1. str.insert(0, 4 - s.size(), '0'); 是用來高位補0的,

 basic_string& insert( size_type index, size_type count, CharT ch ); 意思是,在index處插入count個字符ch

當字符串str爲 22的時候,str.size() = 2, 因此在 index = 0處插入 4 - 2 = 2 個字符 '0'

這樣就實現了高位補0

想了想,也不須要在高位補0,只要插入相應個數的0就能夠了,畢竟須要對字符串進行排序,在哪裏插入0都無所謂了

相關文章
相關標籤/搜索