Advertisement
MuzammiL5

Count set bits till N

Jul 13th, 2021
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.40 KB | None | 0 0
  1. int countSetBits(int n)
  2. {
  3. n++;
  4. int count = n/2;
  5. int powerof2 = 2;
  6.  
  7. while (powerof2 <= n) {
  8. int totalpairs = n/powerof2;
  9. count += (totalpairs/2) * powerof2; // setbits in pairs
  10. count += (totalpairs&1) ? (n % powerof2) : 0; // left out setbits
  11. powerof2 = powerof2<<1;
  12. }
  13. return count;
  14. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement