1、 给定一个整数N,对应的有一个编码M,M满足的条件是:
a) M与N的位数相同;
b) M的各位之和与N的各位之和相等;
c) M是大于N的最小整数。
记M=f(N)。
如果不存在这样的M,则记这个N对应的编码为-1。
现在给定一个初始编码N,N的位数不超过1000位,N的大小不超过10^500,输出序列S(N)。已知S(0) =N,S(1) =f(N),S(2)=f(S(1))……
如果S(i+1) = -1,则停止输出。
解答:
#include<iostream>
using namespace std;
#include<string.h>
int MakeCode(char *nstr, char*mstr)
{
strcpy(mstr,nstr);
int end=strlen(nstr)-1;
int right=end;
while(right>=0&&mstr[right]=='0')
{//find the firt number which is not 0
right--;
}
if(right<=0)
{//all are 0, not exit M
return 0;
}
int right0=right;
right--;
int right1=right;
while(right>=0&&mstr[right]=='9')
{//find the first which is not 9
right--;
}
if(right<0)
{//number left are all 9, not exist M
return 0;
}
mstr[right]++;
mstr[right0]--;
right++;
while(right<end)
{//reverse the numbers at the right of the first number which is not 9.
char temp=mstr[right];
mstr[right]=mstr[end];
mstr[end]=temp;
right++;end--;
}
return 1;
}
void main()
{
char nstr[]="0134";
char *mstr=(char*)malloc(strlen(nstr)+1);
while(1)
{
if(MakeCode(nstr,mstr))
{
cout<<mstr<<endl;
strcpy(nstr,mstr);
}
else
{
cout<<"-1"<<endl;
break;
}
}
getchar();
}
在此多谢W同学复原出这个题目。