HDU - 5491 The Next(思维&二进制)

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值