HDU 5969 最大的位或 【贪心】

Sample Input              

    5
    1 10
    0 1
    1023 1024
    233 322
   1000000000000000000 1000000000000000000

Sample Output

   15
   1
   2047
   511
   1000000000000000000

原题链接

解题思路:

        先将数字转换成二进制存储,这时分情况讨论

              1,如果两个字符串长度相同时,从高位忘低位遍历,直到遇到不一样的(r=1&&l==0,这个条件也是限制了r>l的这个条件)停止 ,把r之后的位数全变成1

             2,如果俩个字符串长度不相同时,r的长度肯定大于l,将r与l相对的位置全部变为1,(r的长度大,r一定是大于L,在这种情况下,让1的个数越多最后结果越大)        

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N =1010;
int a[N],b[N],c[N];
int main(){
  ll y,x;
  ll t;
  cin>>t;
  while (t--) {
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
   cin>>x>>y;
   int lenx=0;int leny=0;
   while(x){
      if(x&1){
        a[lenx++]=1;
      }else a[lenx++]=0;
      x=x>>1;
          }
          while(y){
             if(y&1){
               b[leny++]=1;
             }else b[leny++]=0;
             y=y>>1;
                 }
        if(lenx<leny){
          for(int i=0;i<leny;i++)
             c[i]=1;
        }else{
          ll  i;
          for(i=leny-1;i>=0;i--){
             if(i<lenx&&b[i]==1&&a[i]==0){
               break;
             }else{
               c[i]=b[i];
             }
          }
          for(;i>=0;i--)
             c[i]=1;
        }

        ll ans=0;ll p=1;
        for(int i=0;i<leny;i++){
          if(c[i])ans+=p;
          p*=2;
        }
           cout<<ans<<endl;
  }

  return 0;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@居安

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

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

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

打赏作者

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

抵扣说明:

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

余额充值