1069. The Black Hole of Numbers (20)

本文介绍了一个有趣的数学现象——6174猜想,并详细解释了如何通过编程实现这一猜想的过程。无论初始四位数是多少(数字不全相同),经过特定步骤后都将得到6174这个数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 6174猜想 ,1955年,卡普耶卡(D.R.Kaprekar)研究了对四位数的一种变换:任给出四位数k0,用它的四个数字由大到小重新排列成一个四位数m,再减去它的反序数rev(m),得出数k1=m-rev(m),然后,继续对k1重复上述变换,得数k2.如此进行下去,卡普耶卡发现,无论k0是多大的四位数, 只要四个数字不全相同,最多进行7次上述变换,就会出现四位数6174.

2.需要注意输入的数字不一定是4位的,需要转化为4位的string进行处理,如输入1,2,3,4

3.输入为6174时,应该输出7641 - 1467  = 6174。一开始卡在这个测试点了


//#include<string>
//#include <iomanip>
//#include<stack>
//#include<unordered_set>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<unordered_map>
#include<set>
#include<queue>
#include<map>
#include<vector>
#include <algorithm>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
#include<stack>
using namespace std;
/*
测试案例(不一定是4位数):
6174
需要输出7641 - 1467 = 6174

1

2

3

4

5

6
*/
bool cmp(const char&a, const char&b)
{
	return a > b;
}
string num2str(int a)
{
	a += 10000;//如果有0,则相当于补充千位,百位的0
	string ans = "";
	for (int i = 1; i < 5; i++)
	{
		char c = a % 10 + '0';
		ans = c + ans;
		a /= 10;
	}
	return ans;
}
int str2num(string s)
{
	return (s[0] - '0') * 1000 + (s[1] - '0') * 100 + (s[2] - '0') * 10 + (s[3] - '0');
}
int main(void)
{
	int num;
	cin >> num;
	string s = num2str(num);
	char c = s[0];
	bool isSame = true;
	for (int i = 0; i < 4; i++)
	{
		if(s[i] != c)
		{
			isSame = false;
			break;
		}
	}
	if (isSame)
	{//如果所有位相同,直接输出0000
		cout << s << " - " << s << " = 0000" << endl;
	}
	else
	{
		string ans = "";//这样处理使得输入为6174时,也能输出7641 - 1467 = 6174
		while (ans != "6174")
		{
			sort(s.begin(), s.end(), cmp);
			string a = s;//大到小排列
			sort(s.begin(), s.end());
			string b = s;//小到大排列
			int tmp = str2num(a) - str2num(b);
			ans = num2str(tmp);
			cout << a << " - " << b << " = " << ans << endl;
			s = ans;

		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值