Created
May 25, 2017 21:49
-
-
Save BiruLyu/66bf80643be1b58416fa87a124e72a10 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| // you need to treat n as an unsigned value | |
| public int hammingWeight(int n) { | |
| int count = 0; | |
| while(n != 0){ | |
| n = n & (n-1); | |
| count++; | |
| } | |
| return count; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*In the following solution: | |
| Iterate over 32 bits since its a 32-bit integer. This will be O(1) since it is in constant time | |
| Left shift the number by i to get the LSB value | |
| Do an AND of the number obtained from step 2 with 1. If the result of the AND is 1 then increment the count because the LSB value of that bit was 1. | |
| */ | |
| public int hammingWeight(int n) { | |
| int count = 0; | |
| for(int i=0; i<32; i++){ | |
| count += (n >> i & 1) == 1 ? 1: 0; | |
| } | |
| return count; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment