[Java] 191. The number of bit 1---review java bit operators to avoid a day of stepping on the pit! ! !

Write a function, the input is an unsigned integer (in the form of a binary string), and returns the number of digits in the binary expression whose digits are '1' (also called Hamming weight).

prompt:

Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both input and output will be designated as signed integer types, and should not affect your implementation, because the internal binary representation is the same regardless of whether the integer is signed or unsigned.
In Java, the compiler uses two's complement notation to represent signed integers. Therefore, in example 3 above, the input represents a signed integer -3.

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: In the input binary string 00000000000000000000000000001011, a total of three bits are '1'.
Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: In the input binary string 00000000000000000000000010000000, a total of one bit is '1'.
Example 3:

Input: 11111111111111111111111111111111101
Output: 31
Explanation: In the input binary string 11111111111111111111111111111101, a total of 31 bits are '1'.

prompt:

The input must be a binary string of length 32.

Advanced:

If you call this function multiple times, how would you optimize your algorithm?

复习;
a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

下面的表中列出了按位运算符,假设整数变量A=60,变量B=13,那么 -

运算符

描述

示例

&

二进制AND运算符,如果存在于两个操作数中,则它会将结果复制到结果中。

A&B的结果为:12,也就是:0000 1100

Ι

二进制OR运算符,如果存在于任一操作数中,则复制一位。

A|B 的结果为:61,也就是:0011 1101

^

二进制异或运算符,如果在一个操作数中设置但不在两个操作数中设置,则复制该位。

A^B的结果为:49,也就是:0011 0001

~

二元一元补充运算符是一元的,具有“翻转”位的效果。

~A的结果为:-61,也就是:1100 0011

<<

二进制左移运算符,左操作数值向左移动右操作数指定的位数。

A << 2的结果为:240,也就是:1111 0000

>>

二进制右移运算符,左操作数值向右移动右操作数指定的位数。

A >> 2的结果为:15,也就是:1111

>>>

右移零填充运算符。 左操作数值向右移动右操作数指定的位数,移位值用零填充。

A >>>2的结果为:15,也就是:0000 1111
代码:
 public int hammingWeight(int n) {
    
    
    	 int sum=0;
		 for(int i=0;i<32;i++) {
    
    
			 if((n>>i&1)==1) {
    
    
				sum++; 
			 }
		 }
    	 return sum;  
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115065929