百度2012校园招聘 笔试题(深圳)

来源:互联网 发布:数据质量问题库设计 编辑:程序博客网 时间:2024/04/29 00:19
 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 0right--;}if(right<=0){//all are 0, not exit Mreturn 0;}int right0=right;right--;int right1=right;while(right>=0&&mstr[right]=='9'){//find the first which is not 9right--;}if(right<0){//number left are all 9, not exist Mreturn 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同学复原出这个题目。

上面是粗陋的解答,还请各位不吝赐教!