您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: