多开了一维first,判断此时是否有前导0,不考虑前导0
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#define maxn 30
using namespace std;
#define ll long long
int limit[40],dp[40][40][40];
int dfs(int now,int prev,int have,int first,bool flag)
{//prev存储0的个数,have存储1的个数,first存储此时是否含有前导0
if(now<=0)
{
if(first) return prev>=have;
else return 0;
}
if(!flag&&dp[now][prev][have]!=-1&&first) return dp[now][prev][have];
int bound=flag?limit[now]:1,ret=0;
for(int k=0;k<=bound;k++)
{
if(first)
{
ret+=dfs(now-1,prev+!k,have+k,first,flag&&(k==bound));
}
else
{
if(k==0)
ret+=dfs(now-1,0,0,0,flag&&(k==bound));
else
ret+=dfs(now-1,0,1,1,flag&&(k==bound));
}
}
if(!flag) dp[now][prev][have]=ret;
return ret;
}
int count(int x)
{
int len=0;
while(x)//使用位运算得到x中每位的值
{
limit[++len]=x&1;
x>>=1;
}
return dfs(len,0,0,0,true);
}
int main()
{
int n,m;
memset(dp,-1,sizeof(dp));
while(cin>>n>>m)
{
cout<<count(m)-count(n-1)<<endl;
}
return 0;
}