Codeforces Round #279 (Div. 2) C.Hacking Cypher 找规律

C.Hacking Cypher

题意:

给你一个区间 [L,R] ,求区间内任意两个数相异或的最大值。

题解:

1       00001
2       00010
3       00011
4       00100
5       00101
6       00110
7       00111
8       01000
9       01001
10     01010
11     01011
12     01100
13     01101
14     01110
15     01111
16     10000   

找规律可以发现任意区间 [L,R] 内相异或最大的值为 L和R 的二进制中最高的不相同的位置起(包含这一位)往后全变为1的值。

例如:8  16  从高位开始比,第一位就不同,所以值为 11111

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<string>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define mod 1000000007
using namespace std;
typedef long long ll;
int main()
{
    ll a,b;
    scanf("%I64d %I64d",&a,&b);
    if(a==b)
    {
        printf("0\n");
        return 0;
    }
    bitset<60> fa(a);  //把a转换为60位的二进制
    bitset<60> fb(b);
    int k = 0;   //最高位不同的位置
    for(int i=59;i>=0;i--)
    {
        if(fa[i]!=fb[i])
        {
            k = i;
            break;
        }
    }
    ll ans = 1;
    while(k--)
        ans = (ans<<1)+1;
    printf("%I64d\n",ans);
    return 0;
}

还有一种简单的写法

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<string>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define mod 1000000007
using namespace std;
typedef long long LL;
int main()
{
    LL a,b;
    int i;
    scanf("%I64d %I64d",&a,&b);
    for( i=63;i>=0;i--)
    {
        if( (a & (1LL<<i)) ^ (b & (1LL<<i)) )
            break;
    }
    LL ans = pow(2,i+1)-1;
    printf("%I64d\n",ans);
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值