Problem : Numbers That Count
Description:给你一串数字,例如111222234459,里边有3个1,4个2,1个3,2个4,1个5,1个9,所以新形成的字符串为314213241519,然后接着计算新的字符串中每个数字的个数。问多少次以后这个字符串能变成之前一样的字符串。
Solution:递归。主要要注意字符串与int型之间的转换。
Code(C++):
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
int count[10];
string str[20];
int a[80];
int i,j,t,length;
void compare(string s,int k)
{
if(k==16)
{
cout<<str[0]<<" can not be classified after 15 iterations"<<endl;
return;
}
str[k]="";
length=s.size();
for(i=0; i<length; i++)
a[i]=s.at(i)-'0';
memset(count,0,sizeof(count));
int i;
for(i=0; i<length; i++)
count[a[i]]++;
for(i=0; i<10; i++)
{
if(count[i]==0)
continue;
/*char tmp[78];
_itoa(count[i],tmp,10);
str[k]+=string(tmp);
_itoa(i,tmp,10);
str[k]+=string(tmp);*/
char sr[5]="",t[5]="";
sprintf(sr,"%d",count[i]);
sprintf(t,"%d",i);
str[k]+=string(sr);
str[k]+=string(t);
}
for(i=k-1; i>=0; i--)
{
if(str[k]==str[i])
{
if(i==0&&k-i==1)
cout<<str[0]<<" is self-inventorying"<<endl;
else if(k-i==1)
cout<<str[0]<<" is self-inventorying after "<<i<<" steps"<<endl;
else
cout<<str[0]<<" enters an inventory loop of length "<<k-i <<endl;
return ;
}
}
compare(str[k],k+1);
}
int main()
{
string s;
while(cin>>s,s!="-1")
{
t=1;
str[0]=s;
compare(s,t);
}
return 0;
}