Lowest bit of binary 1

Learn how to find the lowest bit 1 of a number

  • Complement:
    ① The complement of a positive number is itself;
    ② The complement of a negative number:
例如负数为a,对应正数为b,利用a+b=0

写负数a补码的方法1:先填符号位1,其余位在b的基础上全部取反,再+1
最高位是1,其余所有位a和b相反,因此a+b=1,再+1溢出为0;

写负数a补码的方法2:在b基础上,保留最低位1和右侧的0不变,再把左侧全部位取反
例如b的最低位1100,且左侧全部位相反,因此a+b会因为相同的最低位100导致溢出为0
  • Find the lowest bit of a number 1: the
    optimal solution O(1): Take the previous method 2 as an example, the lowest bit 100 of x and -x are the same, and the rest are opposite, so x & (-x) will Get 100

This method can only judge x from the lowest bit bit by bit, O(sizeof(type) * 8)

  • Find the k-th binary of a number x: x >> k & 1

  • Count the number of binary 1s of a number int x:

//简单写法:不改变原数
int cnt = 0;
for (int k = 0; k < 32; ++k) {
    
    
	if (x >> k & 1) ++cnt;
}

//更快,但会修改原数字
int cnt = 0;
while (x) {
    
    
	x &= (x - 1);//x&(x-1)会去掉自己最低位的1
	++cnt;
}

Guess you like

Origin blog.csdn.net/jiuri1005/article/details/114898743