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。一开始卡在这个测试点了。
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 — the “black hole” of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767, we’ll get:
7766 – 6677 = 1089
9810 – 0189 = 9621
9621 – 1269 = 8352
8532 – 2358 = 6174
7641 – 1467 = 6174
… …
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0, 10000).
Output Specification:
If all the 4 digits of N are the same, print in one line the equation “N – N = 0000”. Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.
Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000
AC代码:
[c language=”++”]
//#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;
}
[/c]