观察下面:
输入1234,
4321 - 1234 = 3087;
8730 - 378 = 8352 ;
8532 - 2358 = 6147;
7641 - 1467 = 6174;
一直到出现相同的数字后退出;
例如:
1234
1234 -> 3087->8352 ->6147 ->6147
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int get_next(int x){
int a;
int b;
char t;
char s[10];
sprintf(s,"%d",x);
int len = strlen (s);
for(int i = 0; i < len - 1 ; i ++ )
for (int j = 0;j < len - 1- i ; j ++ ){
if(s[j] > s[j+1])
{
t = s[j];
s[j] = s[j+1];
s[j+1] = t;
}
}
sscanf(s,"%d",&a);
for(int i = 0 ;i < len/2 ; i ++){
t = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = t;
}
sscanf(s,"%d",&b);
return b - a ;
}
int main(){
int num[1000];
int count;
scanf("%d",&num[0]);
count = 1;
printf("%d",num[0]);
while(1){
num[count] = get_next(num[count - 1]);
printf(" -> %d",num[count]);
int flag ;
for(int i = 0 ;i < count ;i ++)
if(num[i] == num[count])
flag = 0;
if(flag)
count ++ ;
else
break;
}
printf("\n");
return 0;
}