位运算按位与

#include <stdio.h>

int getPo(int);
int findPo(int a, int b, int p);
int rangeBitwiseAnd(int m, int n);

void main(){
    int x = 59, y = 63, px, py, count, res;
    count = rangeBitwiseAnd(x, y);
}

int rangeBitwiseAnd(int m, int n){
    if(m==0 || n==0){
        return 0;
    }
    if(m==n){
        return m;
    }
    int px, py, count,res;
    px = getPo(m);
    py = getPo(n);
    if(px!=py){
        //printf("0\n");
        return 0;
    }else{
        count = findPo(m,n,px);
        res = (m>>(count))<<(count);
        //printf("res:%d\n",res);    
        return res;
    }
}

int getPo(int n){
    int count = 0;
    while(n>0){
        n = n>>1;
        count++;
    }
    //printf("getPo:%d\n",count);
    return count;
}

int findPo(int a, int b, int p){
    int pa, pb;
    p--;
    a = a-(1<<(p));
    b = b-(1<<(p));
    pa = getPo(a);
    pb = getPo(b);
    while(pa==pb && pa>0 && pb>0){
        pa --;
        a -= (1<<(pa));
        b -= (1<<(pa));
        pa = getPo(a);
        pb = getPo(b);
    }
    if(pa>pb){
        p = pa;
    }else{
        p = pb;
    }
    //printf("findPo:%d\n",p);
    return p;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值