Description
给定一个正整数 (n le 10^9),找出小于或等于 (n) 的非负整数中,其二进制表示不包含连续的 (1) 的个数。
Solution
(f(i,j,full)) 表示从高到低处理到第 (i) 位,第 (i) 位是 (j),当前是否贴合上界。对 full=0
的情况记忆化一下即可。
class Solution {
public:
int f[35][2];
Solution()
{
memset(f,-1,sizeof f);
}
int solve(int pos,int last,int full,vector<int>& a)
{
if(pos<0) return 1;
if(!full&&~f[pos][last]) return f[pos][last];
int lim=full?a[pos]:1;
int ans=0;
for(int now=0;now<=lim;now++)
{
if(last==1&&now==1) continue;
ans+=solve(pos-1,now,full&&now==a[pos],a);
}
if(!full) f[pos][last]=ans;
return ans;
}
int findIntegers(int num)
{
vector <int> a;
while(num)
{
a.push_back(num&1);
num>>=1;
}
if(a.size()==0) return 0;
return solve(a.size()-1,0,1,a);
}
};