阿里編程題

定義如下的數列
224610: 2+2=4,2+4=6,4+6=10
2911203151: 2+9=11,9+11=20,11+20=31,20+31=51
給出程序判斷一個數是否滿足此條件

如下解法,僅供參考

#include<string>
#include<iostream>
#include<sstream>

using namespace std;

typedef long long int my_int;

// 聲明
bool judge(my_int);
bool judge_n(string, my_int);
my_int str_to_num(string);
string num_to_str(my_int);


bool judge(my_int num)
{
	stringstream stream;
	stream << num;
	string str;
	stream >> str;
	my_int length = str.size();

	// 不足 3 位數
	if(length < my_int(3))
		return false;

	// 首次可以取的最大位數
	my_int max_n = my_int( length / 3);
	
	for(my_int i=1; i< max_n+1; ++i)
	{
		if(judge_n(str,i))
			return true;
	}
	
	return false;
}

bool judge_n(string str, my_int n)
{
	my_int length = str.size();
	stringstream stream;
	my_int a,b,c;
	string str_a,str_b,str_c;
	
	my_int pos = 0;
	a = str_to_num(str.substr(pos,n));
	pos += n ;    // 移動 a 的位數
	b = str_to_num(str.substr(pos,n));
	c = a+b;
	str_c = num_to_str(c);
	my_int c_length = str_c.size();
	pos += n;    // 移動 b 的位數
	
	// pos 從 0 開始計數
	while(pos + c_length < length+2 )
	{
		// 說明在位數上可以獲取成功
		// 判斷是否滿足數列條件
		my_int get_c_num = str_to_num(str.substr(pos,c_length));
		if( c != get_c_num )
			return false;

		// 滿足數列條件,需要在原數上移動 c_length 個位數,即 c 的位數
		pos += c_length;
		a = b;
		b = c;
		c = a+b;
		str_c = num_to_str(c);
		c_length = str_c.size();
	}

	// pos 移動至 length 下一個位置,但是 pos 從 0 開始計數,此時正好 pos == length
	if( pos == length)
		return true;
	else
		return false;


}

my_int str_to_num(string str)
{
	stringstream stream(str);
	my_int num;
	stream >> num;

	return num;
}

string num_to_str(my_int num)
{
	stringstream stream;
	stream << num;
	string str;
	stream >> str;

	return str;
}


int main()
{
	my_int num1 = 224610;
	my_int num2 = 224611;
	my_int num3 = 2911203151;

	//cout<< (judge(num1)? 1:0) <<endl;
	//cout<< (judge(num2)? 1:0) <<endl;
	cout<< (judge(num3)? 1:0) <<endl;

	system("pause");

}

測試結果:
num1, num3 測試通過,num2 不滿足要求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章