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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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<

 

你可能感兴趣的:(思维)