Little Girl and Maximum XOR(区间最大异或值--技巧)-------------C语言——菜鸟级

本文介绍了一种解决最大异或值问题的方法。给定一对整数l和r,任务是找到所有a和b (l ≤ a ≤ b ≤ r) 对中a ^ b的最大值。通过比较l和r的二进制表示,找到第一个不同的位,并在此基础上构造最大异或值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A little girl loves problems on bitwise operations very much. Here’s one of them.
You are given two integers l and r. Let’s consider the values of for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones.
Expression means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as “^”, in Pascal — as «xor».
Input
The single line contains space-separated integers l and r (1 ≤ l ≤ r ≤ 1018).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
In a single line print a single integer — the maximum value of for all pairs of integers a, b (l ≤ a ≤ b ≤ r).
Example
Input
1 2
Output
3
Input
8 16
Output
31
Input
1 1
Output
0

【题解】
首先,异或值要为1,那么两个数的对应二进制位要不同,而异或值要最大,则二进制的高位要尽可能的为1,所以这就是切入点,从给定的区间上下限入手(l和R),从l和r二进制的最高位开始比较,如果出现对应位异或值位1,就从该处开始,低位都置为1,此时其表示的数就是最大异或值了。

#include<stdio.h>
int  main()
 {
 long long l,r,t,w;
 while(scanf("%lld%lld",&l,&r)!=EOF)
 {  
   if(r==l)printf("0\n");
   else
   {w=0;
       while(r!=l&&r!=0)//相等或最大值为0 结束                101011 
       {                //相等则证明 此位之前的异或不可能为1  101110 
          w++;
          l=l>>1;//从右向左移动 
          r=r>>1;
       }
        t=1;
       while(w--)t=t*2;
       printf("%lld\n",t-1); 
   }
 }
   return 0;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Five-菜鸟级

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值