Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as thehamming weight ).
For example, the 32-bit integer ' One ' 00000000000000000000000000001011
has a binary representation, so the function should return 3.
Solution 1:
It seems to be a very simple subject, but it is flawed when you do it.
Idea: Save a count, each time n to the right one bit, check whether the last one is 1, is 1 will count plus one.
Note that the shift number does not change the value itself, but it is not allowed to be assigned.
Pay attention to the situation of overflow, so you can not put N in the condition of while to make judgments.
Bit manipulation Ref:
Http://www.tutorialspoint.com/java/java_basic_operators.htm
Public classSolution {//You need to treat N as an unsigned value Public intHammingweight (intN) {intCount=31; intRes=0; while(count>=0) { if((n&1)!=0) {res++; } N=n>>>1; Count--; } returnRes; }}
Solution2:
See discussion, incredibly have a cheat Method!!!
return Integer.bitcount (n);
Solution3:
Public classSolution {//You need to treat N as an unsigned value Public intHammingweight (intN) {intCount = 0; intMask = 1; inti = 0; while(I < 32) { if((n&mask)! = 0) {Count++; } Mask<<= 1; I++; } returncount; }}
The idea is the same as 1, but this is every time I move. Shorthand for shift: <<=,>>=. >>> three arrows is fill left by 0.
Solution 4:
public class solution { // public int hammingweight ( N) { int count = 0; for (count = 0; n! = 0; Count++ &= n-1; // Clear the least significant bit set count; }}
This solution is so ingenious! The rightmost 1 is cleared, and the number of 1 is zeroed out how many times. Then accumulate the number of times
111000 & 110111=110000
110000 & 101111 =100000
100000 & 011111 =000000
191. Number of 1 Bits