2015年ACM-ICPC亚洲区域赛合肥站网络预选赛H题——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 XHY number if S1≤L≤S2.
With a given D, we would like to find the next XHY number Y, which is JUST larger than D. In other words, is the smallest XHY number among the numbers larger than D. Please write a program to solve this problem.


输入要求
The first line of input contains a number T indicating the number of test cases (T≤100000).
Each test case consists of three integers D, S1, and S2, as described above. It is guaranteed that 0≤D<2^28 and D is a XHY number.

输出要求

For each test case, output a single line consisting of “Case #X: Y”. X is the test case number starting from 1. Y is the next XHY number.

测试数据示例
输入
3
11 2 4
22 3 3
15 2 5
输出
Case #1: 12
Case #2: 25
Case #3: 17
 
大水题,开始以为会TLE,结果暴力搞一下位运算就过了,主要是题目有难懂。
 
题目意思大概如下:
L代表整数D的二进制位为1的个数。譬如D=3,L=2。
假如s1<=L<=s2,则D就是XHY数。现在就是要你找出大于D的最小XHY数。
 
题目明白了之后就是很裸的按位与(&)操作。
 
上代码了.
C code
 
#include <stdio.h>

int slove(int d,int s1,int s2){
    int next;
    long end =  1 << 28;
    for(int i=d+1;i<=end;i++){
        int bitCount = 0;
        for(int j=0;j<31;j++){
            if( (i & (1<<j)) > 0) bitCount++;
        }
        if(bitCount>=s1 && bitCount <= s2){
           next=i;
           break;
        }
    }
    return next;
}
int main(){
    int n;
    int d;
    int s1;
    int s2;
    int c = 1;
    while(scanf("%d",&n)==1){
        for(int i=0;i<n;i++){
            scanf("%d",&d);
            scanf("%d",&s1);
            scanf("%d",&s2);
            int ret = slove(d,s1,s2);
            printf("Case #%d: %d\n",c++,ret);
        }
    }
}

 

 
 

转载于:https://www.cnblogs.com/dick159/p/5386951.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值