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