浙江大学PAT_甲级_1069. The Black Hole of Numbers (20)
来源:互联网 发布:淘宝卖家用什么app聊天 编辑:程序博客网 时间:2024/05/18 00:55
题目链接:点击打开链接
这题后来在乙级考试里一模一样地出现过。
给定任一个各位数字不完全相同的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 = 10899810 - 0189 = 96219621 - 1269 = 83528532 - 2358 = 6174输入样例2:
2222输出样例2:
2222 - 2222 = 0000
#include<iostream>#include<algorithm>#include<iomanip>using namespace std;int transform(int *num,bool flag)//将数组里的元素合并成一个int数字{//flag=0是表示数字递增,flag=1是表示数字递减。int result = 0,d=1;int i ;if (flag == 0){i = 0;while (i < 4){result = result * 10 + num[i];i++;}}else if (flag==1){i = 3;while (i >= 0){result = result * 10 + num[i];i--;}}return result;}int main(){int i = 0;int num[4] = {0};int result =0;cin >> result;//输入一个数字do{for(i=0;i<4;i++)//将数字从低位到高位保存到数组{num[i] = result % 10;result = result / 10;}sort(num, num + 4);//数组递增排序result = transform(num, 1) - transform(num, 0);cout << setfill('0') << setw(4) << transform(num, 1) << " - " << setfill('0') << setw(4) << transform(num, 0);cout<< " = " << setfill('0') << setw(4) << result << endl;// setfill('0') << setw(4) 设置输出宽度为4,不足部分用0补全,头文件是#include<iomanip>} while (result>0&&result<10000&&result != 6174);//system("pause");return 0;}
0 0
- 浙江大学PAT_甲级_1069. The Black Hole of Numbers (20)
- PAT(甲级)1069. The Black Hole of Numbers (20)
- PAT甲级练习1069. The Black Hole of Numbers (20)
- 【PAT甲级】1069. The Black Hole of Numbers (20)
- PAT 甲级 1069. The Black Hole of Numbers (20)
- [PAT-甲级]1069.The Black Hole of Numbers
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- A1069 . The Black Hole of Numbers (20)
- 1069. The Black Hole of Numbers (20)
- S7-300 PLC的5种定时器
- Esper入门简介:四、 由上篇三我们实现个简单的报警作用吧
- CSS3 Loading效果
- ubuntu 14.04 无法播放视频
- FLAH中影片剪辑与图形元件的不同应用
- 浙江大学PAT_甲级_1069. The Black Hole of Numbers (20)
- 数据结构——链式栈(c++)
- CSS3制作半透明边框记得以前Facebook有段时间使用了非常多的半透明边框(Facebox)
- POJ 1125 Stockbroker Grapevine(Floyd)
- shell的初始化文件:/etc/profile和/etc/bashrc(bash.bashrc)
- Android Service 线程问题
- C#中this关键字详解
- 网易的笔试题
- 用vagrant启动VirtualBox时出错