比赛的时候这道题将我卡住了,赛后看看这道题还是比较简单的;
题目链接:http://codeforces.com/problemset/problem/611/B
题目大意:
给你两个数字a, b; 问有多少x (x >= a && x <= b) 满足二进制数中所含数字0 的数量为1; 如 201510 == 111110111112 符合题目要求;
直接枚举 二进制数中包含0的数量为1的数 x; 如果x 满足 (x >= a && x <= b) ans++;
#include <bits/stdc++.h>
using namespace std;
#define LL long long
int main()
{
LL a, b;
scanf("%I64d%I64d", &a, &b);
int res = 0;
for(int i = 0; (1LL << i)/2 <= b; ++i){
for(int j = 0; j <= i-2; ++j){
long long x = (1LL << i)-1 - (1LL << j);
if(x <= b && x >= a) res++;
}
}
printf("%d\n", res);
}
这里我贴上tourist 的代码 类似的思想,使用递推函数做的:
#include <bits/stdc++.h>
using namespace std;
long long a, b;
long long ans;
void dfs(long long x, int cnt) {
if (x > b) {
return;
}
if (a <= x && x <= b && cnt == 1) {
ans++;
}
if (cnt == 0) {
dfs(x * 2, cnt + 1);
}
dfs(x * 2 + 1, cnt);
}
int main() {
cin >> a >> b;
ans = 0;
dfs(1, 0);
cout << ans << endl;
return 0;
}