PAT_Basic 1019
2016-03-08 17:13
447 查看
/* 给定任一个各位数字不完全相同的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 */ #include <string> #include <iostream> #include <vector> #include <algorithm> using namespace std; bool comp_s(int a, int b){ return a<b; } bool comp_b(int a, int b){ return a>b; } void trans(int in,char a[4], char b[4], char c[4]){ int tmp[4] = { 0 }; for (int i = 3; i > -1; i--){ tmp[i] = in / (pow(10, i)); in = in - tmp[i]*(pow(10, i)); } int tmp_c, tmp_a, tmp_b; tmp_c = tmp_a = tmp_b = 0; sort(tmp, tmp+4, comp_s); for (int i = 0; i < 4; i++){ b[i] = tmp[i]+'0'; tmp_b += (pow(10, (3 - i)))*tmp[i]; } sort(tmp, tmp + 4, comp_b); for (int i = 0; i < 4; i++){ a[i] = tmp[i] + '0'; tmp_a += (pow(10, (3 - i)))*tmp[i]; } tmp_c = tmp_a - tmp_b; for (int i = 0; i < 4; i++){ int t1 = tmp_c / pow(10, (3 - i)); char t = t1 + '0'; c[i] = t; tmp_c = tmp_c - t1 * (pow(10, (3 - i))); } } void out(char a[4], char b[4], char c[4]){ for (int i = 0; i < 4; i++) cout << a[i]; cout << " - "; for (int i = 0; i < 4; i++) cout << b[i]; cout << " = "; for (int i = 0; i < 4; i++) cout << c[i]; cout << endl; } int mark(char a){ return (a - '0'); } int cmp(char c[4]){ int tmp = 0; for (int i = 0; i < 4; i++) tmp+= mark(c[i])*pow(10,(3-i)); if (tmp == 6174 || tmp == 0) return 0; else return 1; } void main(){ int num_in; cin >> num_in; int end = 1; while (end){ char a[4] = {}; char b[4] = {}; char c[4] = {}; trans(num_in, a, b, c); out(a, b, c); end = cmp(c); num_in = 0; for (int i = 0; i < 4; i++) num_in += mark(c[i])*pow(10, (3 - i)); } system("pause"); }
Just want to build a lib.h to combine all the little algorithm from my code into one and just use them without write again
相关文章推荐
- Swift的一些基本属性3 (可选项)
- JavaScript 解析json例子
- iOS中UIViewController生命周期和响应者链
- hdu3790 最短路径问题<最短路>
- 关于ListView 中有head的时候,有事件要处理的时候,
- node.js微信开发《一》
- java并发编程:线程安全管理类--原子操作类--AtomicStampedReference<V>
- Public key for mysql....rpm is not installed
- 进击的正益工场,2016技术与生态齐头并进
- 分享一种用户密码加密方式
- Leetcode299. Bulls and Cows
- Codeforces--630F--Selection of Personnel(组合数)
- Swift的一些基本属性2 (控制流)
- CodeForces 632A-Grandma Laura and Apples
- Photoshop快速复制图层的几种方法和技巧
- NSInputStream 和 NSOutputStream
- 菜鸟教程 Python100例 之实例29
- Jsoup解析HTML、加载文档等实例
- Codeforces--630F--Selection of Personnel(组合数)
- linux系统Qt调用opencv的编译过程(ubuntu14.04 kylin+qt5.5+opencv2.4.10)