/*20140301 hanting*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int sortd(int a)
{
vector<int> sorta(0);
int d;//d位數
for(d=0;d<10;d++)//將a的每一位數字分開存入sorta陣列
{
if(a==0) break;
sorta.push_back(a%10);
a/=10;
}
sort(sorta.begin(),sorta.end());
reverse(sorta.begin(),sorta.end());
for(int i=0;i<d;i++)
{
a+=(sorta[i]*pow(10.,d-i-1));
}
return a;
}
int R(int a)
{
int Ra=0;
while(a)
{
Ra*=10;
Ra+=a%10;
a/=10;
}
return Ra;
}
int main()
{
int digit;
while(cin>>digit && digit!=0)
{
cout<<"Original number was "<<digit<<endl;
int count=0;
int temp[100]={0};
int i=0;
int n=1;
while(n)
{
temp[i]=digit;
count++;
cout<<sortd(digit)<<" - "<<R(sortd(digit))<<" = "<<sortd(digit)-R(sortd(digit))<<endl;
digit=sortd(digit)-R(sortd(digit));
i++;
for(int j=i-1;j>=0;j--)
{
if(digit==temp[j])
{
n=0;break;
}
}
}
cout<<"Chain length "<<count<<endl<<endl;
}
return 0;
}
/*另一寫法*/
/*20140721 hanting*/
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
void Itoa(int N,char *s,int ary)
{
int i=0;
for(i=0;i<25;i++)
{
s[i]=(N%ary)+48;
N/=ary;
if(N==0) break;
}
reverse(s,s+i+1);
s[i+1]=0;
}
int main()
{
int a;
while(cin>>a ,a)
{
cout<<"Original number was "<<a<<endl;
char s[15];
int chain=0;
int store[1000];
int True=1;
while(True)
{
store[chain]=a;
chain++;
Itoa(a,s,10);
sort(s,s+strlen(s));
a=atoi(s);
reverse(s,s+strlen(s));
int tema=atoi(s);
cout<<s<<" - "<<a<<" = "<<tema-a<<endl;
a=tema-a;
for(int i=0;i<chain;i++)
{
if(a==store[i])
{
True=0;break;
}
}
}
cout<<"Chain length "<<chain<<endl<<endl;
}
return 0;
}
2014年3月1日 星期六
[UVA] 263 - Number Chains
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言