PAT_Basic 1019

本文介绍了一种数学现象,即通过特定操作使四位数最终达到数字黑洞6174,也称为Kaprekar常数的过程。文章提供了一个算法实现示例,用于演示如何从任意四位数出发,经过一系列步骤到达这一神奇数字。
/*
给定任一个各位数字不完全相同的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值