Skip to content

Instantly share code, notes, and snippets.

@Ch-sriram
Created May 28, 2020 14:36
Show Gist options
  • Save Ch-sriram/68f0b06e41a6843fd1f6e81b1f4b1804 to your computer and use it in GitHub Desktop.
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].
// 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