Leetcode 191. Number of 1 Bits
Test instructions
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.
Solution:
1. Common solution: Use 1 shift phase and
1 Public classSolution {2 //You need to treat N as an unsigned value3 Public intHammingweight (intN) {4 intFlag = 1;5 intCount = 0;6 while(Flag! = 0) {7 if((N & flag)! = 0) {8count++;9 }TenFlag = Flag << 1; One } A returncount; - } -}View Code
2. Can give the interviewer to surprise the solution, P80 use minus 1 of the nature: minus 1 is actually the right of a 1 after the position of the reverse, and the original figure and only left the front of the bit.
1 Public classSolution {2 //You need to treat N as an unsigned value3 Public intHammingweight (intN) {4 intCount = 0;5 while(n! = 0) {6count++;7n = N & (n-1);8 }9 returncount;Ten } One}View Code
Sword Finger Offer-java