Created
May 30, 2013 03:53
-
-
Save mutoo/5675627 to your computer and use it in GitHub Desktop.
use recursion to count "1" in number as binary
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
| function count1InBin(n){ | |
| if(n<2) | |
| return n&1; | |
| return count1InBin(n>>1)+(n&1); // note: +'s priority is higher than & | |
| } | |
| console.log(count1InBin(0)); // output: 0 | |
| console.log(count1InBin(1)); // output: 1 | |
| console.log(count1InBin(2)); // output: 1 | |
| console.log(count1InBin(3)); // output: 2 | |
| console.log(count1InBin(15)); // output: 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment