当前位置:网站首页>Example of bit operation (to be continued)

Example of bit operation (to be continued)

2022-06-12 15:47:00 General_ zy

The basic principle

0s A string of 0,1s A string of 1.

x ^ 0s = x      x & 0s = 0      x | 0s = x
x ^ 1s = ~x     x & 1s = x      x | 1s = 1s
x ^ x = 0       x & x = x       x | x = x

position 1 The number of

  1. Write a function , Input is an unsigned integer ( In the form of a binary string ), Returns the number of digits in its binary expression as ‘1’ The number of ( Also known as Han Ming weight ).
  2. The input must be of length 32 Of Binary string .

Loop each bit

func hammingWeight(num uint32) int {
    
	count :=0
	for i:=0;i<32;i++{
    
		//  The result here is uint32 Turn to int
		count+= int((num>>i)&1)
	}
	return count
}

Bit operation properties

For integers n,n & (n−1) The result is that n The last binary representation of 1 become 0.

func hammingWeight(num uint32) int {
    
	count :=0
	for num!=0{
    
		num=num&(num-1)
		count++
	}
	return count
}

To be continued

原网站

版权声明
本文为[General_ zy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121539012080.html