码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1019. 数字黑洞

时间:2017-12-17 23:52:49      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:分享图片   lap   none   temp   ide   prime   content   problem   mat   

1019. 数字黑洞 (20)

给定任一个各位数字不完全相同的4位正整数,如果我们先把4个数字按非递增排序,再按非递减排序,然后用第1个数字减第2个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的6174,这个神奇的数字也叫Kaprekar常数。

例如,我们从6767开始,将得到

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

现给定任意4位正整数,请编写程序演示到达黑洞的过程。

输入格式:

输入给出一个(0, 10000)区间内的正整数N。

输出格式:

如果N的4位数字全相等,则在一行内输出“N - N = 0000”;否则将计算的每一步在一行内输出,直到6174作为差出现,输出格式见样例。注意每个数字按4位数格式输出。

输入样例1:
6767
输出样例1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
输入样例2:
2222
输出样例2:
2222 - 2222 = 0000

自己编写的代码:(感觉比较臃肿,但运行速度还是可以的)
技术分享图片
 1 #include<iostream>
 2 #include<sstream>
 3 #include<math.h>
 4 #include<iomanip>
 5 using namespace std;
 6 void Insertion_sort(int a[],int N){
 7 int i,j; 
 8 for(i=1;i<N;i++){
 9 int temp=a[i];
10 for(j=i;j>0;j--)
11 if(a[j-1]>temp) swap(a[j-1],a[j]);
12 else break;
13 a[j]=temp;
14 }
15 } 
16 int main(){
17 string s;
18 cin>>s;
19 s.insert(0,4-s.length(),0);
20 int a[4];
21 int r=0;
22 while(r!=6174){
23 int m=0,n=0;
24 for(int i=0;i<4;i++)
25 a[i]=s[i]-0;
26 Insertion_sort(a,4);
27     for(int i=0;i<4;i++){
28     m+=a[i]*pow(10,i);
29     n+=a[i]*pow(10,3-i);
30 }
31 r=m-n;
32 cout<<setw(4)<<setfill(0)<<m;
33 cout<<" - "; cout<<setw(4)<<setfill(0)<<n;
34 cout<<" = "; cout<<setw(4)<<setfill(0)<<r<<endl;
35 if(r==0) break;
36 ostringstream os;
37 os<<setw(4)<<setfill(0)<<r;
38 s=os.str();
39 }
40 return 0; 
41 } 
View Code

 下面是一个我十分佩服的大神写的,十分简洁;

 

技术分享图片
 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4  
 5 int main() {
 6     string s;
 7     cin >> s;
 8     int a;
 9     cin >> a;
10     int len = s.length();
11     int t = 0;
12     int temp = 0;
13     t = (s[0] - 0) / a;
14     if ((t != 0 && len > 1) || len == 1) {
15         cout << t;
16     }
17     temp = (s[0] - 0) % a;
18     for (int i = 1; i < len; i++) {
19         t = (temp * 10 + s[i] - 0) / a;
20         cout << t;
21         temp = (temp * 10 + s[i] - 0) % a;
22     }
23     cout << " " << temp;
24     return 0;
25 }
View Code

 

从中学到了许多东西,关于string的一些操作,在看完c++primer后忘光了。在此立下金光闪闪flag,一定会在刷PAT过程中再读一遍。

 


PAT 1019. 数字黑洞

标签:分享图片   lap   none   temp   ide   prime   content   problem   mat   

原文地址:http://www.cnblogs.com/A-Little-Nut/p/8053543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!