https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as the Hamming weigh T).
For example, the 32-bit integer ' One ' 00000000000000000000000000001011
has a binary representation, so the function should return 3.
Problem Solving Ideas:
Finding the number of 1 in binary notation is seemingly simple, but not easy.
First, the simplest binary mathematical method is used to calculate the number of 1 in N. But it's wrong.
public class solution { // public int hammingweight ( N) { int count = 0; while (n > 0) { if (n% 2 = = 1 ++ = N/2; return count; }}
Input: 2147483648 (10000000000000000000000000000000) Output:0 expected:1
The problem is that there is no unsigned int in Java, the int in Java is 32 bits, but the size is -2^16~2^16-1, so the maximum value is only 2147483647.
The following is the solution of two netizens, still using bit arithmetic. method is different, but the truth is consistent.
1. N each and 1 bitwise take, the result is only two possible, 1 or 0. If it is 1, it represents the end of 1,count++.
Note, however, that the right shift of N must use unsigned >>>.
Public classSolution {//You need to treat N as an unsigned value Public intHammingweight (intN) {intCount = 0, mask = 1; while(n! = 0){ //if ((n & 1) = = 1 {can also if((n & 1) = = 1) {Count++; } N= n >>> 1; } returncount; }}
The second method, N, does not move, but uses a mask. Mask each shift left one bit, and n go to the bitwise AND, if the result is not 0, it means that this bit must be 1.
Note that the conditions here must be (N&mask)!=0, but not (n&mask) = = 1, because this is the mask of 1 not the last one.
However, the loop of this method must be performed 32 times, and the method above does not have to be.
Public classSolution {//You need to treat N as an unsigned value Public intHammingweight (intN) {intCount = 0, mask = 1; for(inti = 0; I < 33; i++){ if((N & mask)! = 0) {Count++; } Mask= Mask << 1; } returncount; }}
To summarize, the use of bitwise operations is the actual process of computer computing. Shift left is equal to * *, right shift is/2. &1 is the remainder of/2.
In addition, the addition can also be implemented by bitwise operations. The result of the a+b can be seen as the bitwise operation with no carry and the bitwise operation of the simple carry.
Then, each bit of the operation, no carry is equivalent to a^b, simple carry is (a&b) <<1. Add them together.
In particular, this is actually a recursive operation, and we'll call it recursively for add (a, b), until b==0.
http://guozi149.me/series/coding-interview/831
Https://leetcode.com/discuss/30605/simple-java-solution-bit-shifting
Https://leetcode.com/discuss/31671/value-2147483647-test-include-value-2147483648-system-wrong
Number of 1 Bits