Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.
Example 1:
Input: 5 Output: 5 Explanation: Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
Note: 1 <= n <= 109
给定一个正整数 n,找出小于或等于 n 的非负整数中,其二进制表示不包含 连续的1 的个数。
示例 1:
输入: 5
输出: 5
解释:
下面是带有相应二进制表示的非负整数<= 5:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
其中,只有整数3违反规则(有两个连续的1),其他5个满足规则。
说明: 1 <= n <= 109
解题思路:
将n变成二进制的形式存在字符串中,时间复杂度为O(logn),然后用动态规划;
转移方程:aft = d[i - 2] , aft_aft = d[i - 3] ; d[i]表示小于等于2^(i - 1)的整数中不含连续1的整数个数 ;dp[i]表示小于等于n的二进制前i+ 1位表示的正整数中不包含连续为1的整数个数;
if(s[i] == '0')
{
dp[i] = dp[i - 1] ;
}
else if(s[i] == '1' && s[i - 1] == '0')
{
int t = i < 2 ? 1 : dp[i - 2] ;
dp[i] = t + aft + aft_aft ;
}
else if(s[i] == '1' && s[i - 1] == '1')
{
dp[i] = aft * 2 + aft_aft ;
}
class Solution {
public:
int findIntegers(int num)
{
int cnt = 0 , aft = 1 , aft_aft = 1;
string s ;
if(num == 0) return 1 ;
while(num != 0)
{
s += to_string(num & 1) ;
num = num >> 1 ;
cnt++ ;
}
//cout<<"s == "<<s<<endl;
vector<int> dp(cnt , 0) ;
if(s[0] == '0') dp[0] = 1 ;
else dp[0] = 2 ;
for(int i = 1 ; i < cnt ; ++i)
{
//cout<<"i == "<<i<<endl;
if(s[i] == '0')
{
dp[i] = dp[i - 1] ;
}
else if(s[i] == '1' && s[i - 1] == '0')
{
int t = i < 2 ? 1 : dp[i - 2] ;
dp[i] = t + aft + aft_aft ;
}
else if(s[i] == '1' && s[i - 1] == '1')
{
dp[i] = aft * 2 + aft_aft ;
}
//cout<<"dp[i] "<<dp[i]<<endl;
int temp = aft ;
aft = aft + aft_aft ;
aft_aft = temp ;
}
//cout<<"cnt =="<<cnt<<endl ;
return dp[cnt - 1] ;
}
};