Recently want to brush leetcode practice data structure algorithm and so on, start with the water problem
The title is like this.
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.
Probably is the 32-bit number of numbers is calculated as 1 of the number is the Han-plaintext weight, because the recent review of the basic knowledge of C, read a c and pointer in the operator that chapter there is a explanation of the bit operations, which is to take this topic to explain, the classic is really classic Ah! It can also be seen that some of the major companies of the written examination questions also like from these classic books to find the original question or ideas
Here's a solution:
1 classSolution {2 Public:3 intHammingweight (uint32_t N) {4 intones=0;5 for(; n!=0; n>>=1){6 if((n&1)!=0){7ones++;8 }9 }Ten returnones; One } A};
In a nutshell, it's a loop, and the loop determines if there's 1 in the current number.
It is worth noting that (1) n&1 judge the lowest bit if it is 0 n>>=1 if it is 1 ones plus one means 1 digits plus one
(2) N>>=1 This is a right-shift operation, let's review the shift operation
The first is the left shift operation
Left-shift left-hand-out N-position trailing vacancy with 0 topping
Next is the right shift operation
Right-shift operations are divided into logical right-shift and arithmetic-right-shift, which is different: the logical right shift is similar to the left-shift operation, except that the left-hand position is offset by 0 by moving the N-bit to the right, and the empty position of the right-shift-N-position is filled with the sign bit if the negative number is
And what exactly is the right shift is determined by your compiler.
Of course, there is a small change in this question:
1 classSolution {2 Public:3 intHammingweight (uint32_t N) {4 intones=0;5 for(; n!=0; n>>=1){6 if((n%2)!=0){7ones++;8 }9 }Ten returnones; One } A};
Just change the conditional judgment to (n%2) The!=0 effect is the same as judging whether the current is 1
By the way, is Java running so slow? I don't believe it.
191 Number of 1 Bits