Created
May 28, 2020 14:36
-
-
Save Ch-sriram/68f0b06e41a6843fd1f6e81b1f4b1804 to your computer and use it in GitHub Desktop.
Given a Number - N, count the number of set bits in N [This solution unsets the Least Significant Set Bit of the given N].
This file contains 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
// for previous solution: https://gist.github.com/Ch-sriram/212f8185414fcb71278c6028128fcb2a | |
// Intuition behind the solution: | |
// When we apply bitwise-AND the number N with N-1, we get a new number whose Least Significant Set Bit is Unset. | |
int countSetBits (long long N) { | |
int cnt = 0; | |
while (N != 0) { | |
++cnt; | |
N = N & (N-1); // This is the unsetting step. | |
} | |
return cnt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment