位移运算>>= 和lowbit()

文章目录

位移

10的二进制表示位1010
在这里插入图片描述

lowbit

lowbit(x)返回的最后一位1
x = 1010 lowbit(x) = 10
x = 1010000 lowbit(x) = 10000

#include <iostream>

using namespace std;

int a = 4;
int b = 7;
int c = 10;

int lowbit(int x){
    return x&(-x);
}

int lowbit1(int x){
    return x&(x^(x - 1));
}
int main(){
    cout << lowbit(a) << endl;// 4 = 100   lowbit(4)  = 100 = 2 ^ 2 + 2 ^ 0 + 2 ^ 0 = 4;
    cout << lowbit(b) << endl;// 7 = 111   lowbit(7)  = 1   = 2 ^ 0 = 1;
    cout << lowbit(c) << endl;// 10 = 1010 lowbit(10) = 10  = 2 ^ 1 + 2 ^ 0 = 2;
    
    cout << lowbit1(a) << endl;
    cout << lowbit1(b) << endl;
    cout << lowbit1(c) << endl;
    return 0;
}
/*
结果:
4
1
2
4
1
2
*/
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页