Last active
September 24, 2015 01:26
-
-
Save ps/d3e754e38c29a0970f2e to your computer and use it in GitHub Desktop.
Counting the number of 1 bits in binary representaiton of a number!
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
| So given a number count the number of 1's it has set in it's binary representation. Easy! | |
| Just keep on dividing by two (or bitshift right) and see if the number is odd or even and increment the count based | |
| on this criteria like so: | |
| getNumBitsSet(int val) { | |
| int count=0; | |
| while(val>0) { | |
| if(val % 2 != 0) | |
| count++; | |
| count = count / 2; | |
| } | |
| return count; | |
| } | |
| But what about if the number is negative? Well we know that signed integers are stored using Two's Complement so let's utilize this. | |
| Figuring out a negative representation of a positive number using Two's Complement is as follows: | |
| -flip all bits | |
| -add 1 | |
| So bitshifting won't help us much here so what we can do is bitwise XOR our negative number with the minimum integer value. | |
| This way we will get rid of the '1' bit being set by Two's Complement and we will get a positive number which we will | |
| be able to bitshift as we please so we can do the regular continuously divide by 2 or do an actual bit right shift. | |
| //in code | |
| getNumBitsSet(int val) { | |
| int count = 0; | |
| if(val < 0) { | |
| count++; | |
| val = val ^ Integer.MIN_VALUE; | |
| } | |
| while(val > 0) { | |
| if((val & 1) == 1) | |
| count++; | |
| val = val >> 1; | |
| } | |
| return count; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment