百度2012校園招聘 筆試題(深圳)

 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同學復原出這個題目。

上面是粗陋的解答,還請各位不吝賜教!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章