Let L denote the number of 1s in integer D’s binary representation. Given two integers S1 and S2, we call D a WYH number if S1≤L≤S2.
With a given D, we would like to find the next WYH number Y, which is JUST larger than D. In other words, Y is the smallest WYH number among the numbers larger than D. Please write a program to solve this problem.
- 题意:给定一个数d,和s1,s2,d中1的个数一定在s1,s2之间,我们称d为WYH数,求一个最小的大于d的WYH数。
- 因为要找最小的嘛,先d+1看看,符不符合条件,如果不符合,那么就看看是不是个数多了,多了就在最低位的1再加上1,这样就会消去1,如果1个数不够就在最后0的地方补1
参考题解
没想到这么做,还有num&(num-1)就可以消去最右边一位的1,学到了。感谢大佬的博客。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int eva(int d)
{
int c = 0;
for(; d; c++)
{
d &= (d-1);
}
return c;
}
int main()
{
int t, cas=1;
scanf("%d", &t);
while(t--)
{
int s1, s2, x;
long long d, d1;
scanf("%lld%d%d", &d, &s1, &s2);
d++;
x = eva(d);
while(x > s2)
{
d += d&(-d);
x = eva(d);
}
if(x < s1)
{
int k = 1;
for(int i = 0; i < s1-x; i++)
{
while(d&k) k<<=1;
d |= k;
}
}
printf("Case #%d: %lld\n",cas++,d);
}
return 0;
}