任意一个4位自然数,将组成该数的各位数字重新排列,形成一个最大数和一个最小数,之后两数相减,其差仍为一个自然数,重复进行上述运算,你会发现一个奇妙的数(该数继续运算下去会永远保持不变)。试用C++编程找出这个奇妙的数。
编程高手来看一看,解一解
- 提问者网友:送舟行
- 2021-04-25 05:48
- 五星知识达人网友:忘川信使
- 2021-04-25 06:13
结果为6174,代码如下:
#include <iostream>
using namespace std;
void sort(int *a, int n)
{
int i, j, t;
for(i = 0; i < n - 1; ++i)
for(j = i + 1; j < n; ++j)
if(a[i] < a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int main()
{
int n, m, max, min, a[4];
cout << "输入一个四位数:";
cin >> n;
do
{
m = n;
a[0] = n / 1000;
a[1] = n / 100 % 10;
a[2] = n / 10 % 10;
a[3] = n % 10;
sort(a, 4);
max = a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3];
min = a[0] + a[1] * 10 + a[2] * 100 + a[3] * 1000;
n = max - min;
} while(n != m);
cout << "这个奇妙的数是" << n << endl;
return 0;
}
- 1楼网友:愁杀梦里人
- 2021-04-25 06:50
#include <stdio.h> #include <assert.h>
#define SWAP_IF_GREAT(x, y) \ do { \ if ((x) > (y)) \ { \ unsigned char t = (x); \ (x) = (y); \ (y) = t; \ } \ } while(false)
unsigned short GetStrangenessEx( unsigned char a, unsigned char b, unsigned char c, unsigned char d ) { assert(a <= b); assert(b <= c); assert(c <= d);
unsigned short min = a * 1000 + b * 100 + c * 10 + d; unsigned short max = d * 1000 + c * 100 + b * 10 + a;
unsigned short number = max - min;
unsigned char e = number % 10; number /= 10; unsigned char f = number % 10; number /= 10; unsigned char g = number % 10; number /= 10; unsigned char h = number % 10; number /= 10;
assert(0 == number);
SWAP_IF_GREAT(e, f); SWAP_IF_GREAT(e, g); SWAP_IF_GREAT(e, h); SWAP_IF_GREAT(f, g); SWAP_IF_GREAT(f, h); SWAP_IF_GREAT(g, h);
if ( (e == a) && (f == b) && (g == c) && (h == d) ) { return min; }
return GetStrangenessEx(e, f, g, h); }
unsigned short GetStrangeness( unsigned short number ) { unsigned char a = number % 10; number /= 10; unsigned char b = number % 10; number /= 10; unsigned char c = number % 10; number /= 10; unsigned char d = number % 10; number /= 10;
assert(0 == number);
SWAP_IF_GREAT(a, b); SWAP_IF_GREAT(a, c); SWAP_IF_GREAT(a, d); SWAP_IF_GREAT(b, c); SWAP_IF_GREAT(b, d); SWAP_IF_GREAT(c, d);
return GetStrangenessEx(a, b, c, d); }
int main() { printf("%d\n", GetStrangeness(1234)); return 0; }