6174问题是个黑洞问题.因为所有的4位数,做了正排序,做了逆排序,
最终都会到6174问题而结束循环,,,
这说明了数学的有趣
其实做过一次这个题目,不过忘了是哪一题了
贴出现在的代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
char str[111];
int num[1111];
int getnum(int x)
{
char s[11];
char t1[11];
char t2[11];
sprintf(s,"%d", x); //这个格式化的转化真的是不错!
// cout << "s = " << s << endl;
strcpy(t1,s);
strcpy(t2,s);
int n = strlen(s);
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (t1[i] > t1[j])
{
char t = t1[i];
t1[i] = t1[j];
t1[j] = t;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (t2[i] < t2[j])
{
int t = t2[i];
t2[i] = t2[j];
t2[j] = t;
}
}
}
// cout << "t1 = " << t1 << endl;
// cout << "t2 = " << t2 << endl;
int a = atoi(t2);
int b = atoi(t1);
// cout << "a = " << a << endl;
// cout << "b = " << b << endl;
// cout << "a - b = " << a - b << endl;
return (a - b);
}
void Solve()
{
int cnt = 1;
num[0] = atoi(str);
cout << num[0] << "->";
while (1)
{
num[cnt] = getnum(num[cnt - 1]);
cout << num[cnt];
int found = 0;
for (int i = 0; i < cnt; i++)
{
if (num[cnt] == num[i])
{
found = 1;
break;
}
}
if (found == 1)
{
break;
}
else
{
cout << "->";
}
cnt++;
}
cout << endl;
}
int main()
{
while (scanf("%s", str) != EOF)
{
// cout << getnum(3087) << endl;
Solve();
// int a = getnum(456);
}
system("pause");
return 0;
}