Skip to content

Commit

Permalink
write faster method to count the number of set bits in a given intege…
Browse files Browse the repository at this point in the history
…r in cpp
  • Loading branch information
justanindieguy committed Jan 31, 2023
1 parent 0ad1222 commit 5bcba71
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Bit-manipulationTechniques/CountBits/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,27 @@ int countBits(int n)
return count;
}

// Counting Sets Bits: Hack (faster method)
int countBitsHack(int n)
{
int ans = 0;
while (n > 0)
{
// Removes the last set bit from the current number
n = n & (n - 1);
ans++;
}

return ans;
}

int main()
{
int n;
cin >> n;

cout << countBits(n) << endl;
cout << countBitsHack(n) << endl;

return 0;
}

0 comments on commit 5bcba71

Please sign in to comment.