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;
}