给定一个区间,要求求出该区间内,二进制数中只有一个0的数字的个数;
直接模拟,将十进制转成二进制,直接枚举所有可能的结果
#include<iostream>
#include<cstdio>
#include<set>
#include<string>
#include<string.h>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<cctype>
#include<algorithm>
#include<sstream>
#include<utility>
#include<cmath>
#include<functional>
#define mt(a) memset(a,0,sizeof (a))
#define fl(a,b,c) fill(a,b,c)
#define SWAP(a,b,t) (t=a,a=b,b=t)
#define inf 1000000000+7
#define sp system("pause")
using namespace std;
typedef long long ll;
int main()
{
ll a, b;
cin >> a >> b;
stack<char>sa, sb;
while (a)
{
if (a & 1 )sa.push('1');
else sa.push('0');
a >>= 1;
}
while (b)
{
if (b & 1 )sb.push('1');
else sb.push('0');
b >>= 1;
}
string stra,strb;
while (!sa.empty())
{
stra += sa.top();
sa.pop();
}
while (!sb.empty())
{
strb += sb.top();
sb.pop();
}
string ta, tb;
for (int i = 0; i < stra.size(); i++)
{
ta += '1';
}
for (int i = 0; i < strb.size(); i++)
{
tb += '1';
}
ll ansa = 0, ansb = 0;
if (stra.size() == strb.size())
{
for (int i = ta.size() - 1; i >= 1; i--)
{
if (i != ta.size() - 1)ta[i + 1] = '1';
ta[i] = '0';
if (ta >= stra&&ta <= strb)ansa++;
}
printf("%lld\n", ansa);
}
else
{
for (int i = stra.size() - 1; i >= 1; i--)
{
if (i != stra.size() - 1)ta[i + 1] = '1';
ta[i] = '0';
if (ta >= stra)ansa++;
}
for (int i = strb.size() - 1; i >= 1; i--)
{
if (i != strb.size() - 1)tb[i + 1] = '1';
tb[i] = '0';
if (tb <= strb)ansb++;
}
for (int i = stra.size() + 1; i < strb.size(); i++)
{
ansb += (i - 1);
}
ansb += ansa;
cout << ansb << endl;
}
//sp;
return 0;
}