Cabric Number Problem
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9865 | Accepted: 3001 |
Description
If we input a number formed by 4 digits and these digits are not all of one same value, then it obeys the following law. Let us operate the number in the following way:
(1) Arrange the digits in the way from bigger to smaller, such that it forms the biggest number that could be made from these 4 digits;
(2) Arrange the digits in the way from smaller to bigger, such that it forms the smallest number that could be made from these 4 digits (If there is 0 among these 4 digits, the number obtained may be less than four digits);
(3) Find the difference of these two numbers that is a new four digital number.
Repeat the above process, we can finally always get the result 6174 or 0.
Please write the program to realize the above algorithm.
(1) Arrange the digits in the way from bigger to smaller, such that it forms the biggest number that could be made from these 4 digits;
(2) Arrange the digits in the way from smaller to bigger, such that it forms the smallest number that could be made from these 4 digits (If there is 0 among these 4 digits, the number obtained may be less than four digits);
(3) Find the difference of these two numbers that is a new four digital number.
Repeat the above process, we can finally always get the result 6174 or 0.
Please write the program to realize the above algorithm.
Input
Each case is a line of an integer.-1 denotes the end of input.
Output
If the integer is formed exactly by 4 digits and these digits are not all of one same value, then output from the program should show the procedure for finding this number and the number of repetition times. Otherwise output "No!!".
Sample Input
5364 2221 4444 -1
Sample Output
N=5364: 6543-3456=3087 8730-378=8352 8532-2358=6174 Ok!! 3 times N=2221: 2221-1222=999 999-999=0 Ok!! 2 times N=4444: No!!
题目意思:将一个各位不全相同的4位数各位从新排列,用其中最大的减去最小的,对得到的数字同样操作,最用一定会的6174或0。
解题思路:注意输入的数字必须是4位数,而且所以位数上的数不能全部相同;
#include <iostream>
#include <algorithm>
using namespace std;
bool istrue(int n){
if (999<n&&n<10000){
int last=n%10,a;
n/=10;
while (n>0){
a=n%10;
if (a!=last)
return true;
n/=10;
}
return false;
}
else
return false;
}
int main(){
int n,num[4];
while (cin>>n){
if (n==-1)
break;
cout<<"N="<<n<<":"<<endl;
if (istrue(n)==false)
cout<<"No!!"<<endl;
else{
int count=0;
while (1){
int k=0;
while (n>0){
num[k++]=n%10;
n/=10;
}
sort(num,num+k);
int k1=0,k2=0;
for (int i=0;i<k;i++){
k1=k1*10+num[i];
k2=k2*10+num[k-1-i];
}
n=k2-k1;
count++;
cout<<k2<<"-"<<k1<<"="<<n<<endl;
if (n==0||n==6174){
cout<<"Ok!! "<<count<<" times"<<endl;
break;
}
}
}
}
return 0;
}