问题描述
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:
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.
问题分析
没有连续1的k字符串的长度是斐波那波序列f(k);
例如,如果k=5,范围是00000-11111。我们可以把它看作两个范围,即00000-01111和10000-10111。由于连续的1,任何数字都不允许。第一种情况是f(4),第二种情况是f(3),所以f(5)=f(4)+f(3)
从最重要的数字,即左到右,以二进制的格式扫描数字。如果我们在右边找到k位的“1”,那么计数就会增加f(k)因为我们可以在这个数字上加上一个“0”和任何一个有效的长度k字符串;在那之后,我们继续循环,考虑其余的情况。我们在这个数字上放一个’1’如果找到了连续的1,我们就退出循环并返回答案。在循环结束时,我们返回count+1来包含数字n本身。
例如,如果n是10010110,
我们在右边找到了第一个’1’,我们加上了00000000-01111111,也就是f(7);
第二个“1”在右边的4位数字中,增加了1000000010001111,f(4);
第三个“1”在右边的2个数字中,加上100万-10010011,f(2);
第4个“1”在右边的1个数字,添加范围为10010100-10010101,f(1);
这些范围从00000000到10010101。任何更大的数小于等于n的数都是连续的。
代码展示
#include<iostream>
#include<stdlib.h>
#include<vector>
#include<math.h>
using namespace std;
class Solution {
public:
int findIntegers(int num) {
int f[32];
f[0] = 1;
f[1] = 2;
for (int i = 2; i < 32; ++i)
f[i] = f[i-1]+f[i-2];
int ans = 0, k = 30, pre_bit = 0;
while (k >= 0) {
if (num&(1<<k)) {
ans += f[k];
if (pre_bit) return ans;
pre_bit = 1;
}
else
pre_bit = 0;
--k;
}
return ans+1;
}
};
int main(){
int num;
cin>>num;
Solution solution;
int result=solution.findIntegers(num);
cout<<result<<endl;
}
运行结果展示