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都无所谓了

相关文章
相关标签/搜索