cf 484A

#include<iostream>#include<cstdio>#include<string>#include<string.h>#include<cstring>#include<algorithm>using namespace std;int cal(long long d){
	int len = 0;
	while(d){
		d >>= 1;
		++len;
	}
	return len;}int main(){
	int n;
	scanf("%d", &n);
        long long l, r;
	for(int i = 0; i < n; ++i){
		scanf("%I64d%I64d", &l, &r);
		int rlen = cal(r), llen = cal(l);
		if(rlen > llen){ //length of r is longer than length of l
			if(rlen == (1LL << rlen) - 1){
				printf("%I64d\n", r);
			}
			else{ //number with maximum 1 below r
				printf("%I64d\n", (1LL << (rlen - 1)) - 1);
			}
		}
		else{ 
			for(int i = 0; i < rlen; ++i){ //from low bit to high bit, test if l can be higher
				if((l | (1LL << i)) > l && ((l | (1LL << i)) <= r)){
					l |= 1LL << i;
				}
			}
			printf("%I64d\n",l);
		}
	}
	return 0;}

这道题用了构造的方法,之所以没想到也是因为对位运算不熟悉,看到题目除了枚举没有想到别的好办法,

思路已经在注释里写出来了

 总结一下学到的技巧:

  1. 用逐位右移的方法求一个non-negative integer的位数

  2. if length of a non-negative integer d is len, then 1 << len is larger than d with 1 in the left most

  3. using operator | rather than + can update a specified integer faster





转载于:https://my.oschina.net/u/1421373/blog/379791

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值