阿里编程题

定义如下的数列
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 不满足要求。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值