Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.
示例
示例 1:
输入: n = 5
输出: 5
解释:
下面是带有相应二进制表示的非负整数<= 5:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
其中,只有整数3违反规则(有两个连续的1),其他5个满足规则。
示例 2:
输入: n = 1
输出: 2
示例 3:
输入: n = 2
输出: 3
解题
class Solution {
public int findIntegers(int n) {
int[] dp=new int[31];
dp[0]=1;
dp[1]=1;
for(int i=2;i<31;i++)
dp[i]=dp[i-1]+dp[i-2];
int pre=0,res=0;
for(int i=29;i>=0;i--)
{
int cur=(1<<i);
if((n&cur)!=0)
{
res+=dp[i+1];
if(pre==1)
break;
pre=1;
}else pre=0;
if(i==0)
res++;
}
return res;
}
}
本篇文章来源于微信公众号:程序IT圈
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/22783.html