fork download
  1. #include <stdio.h>
  2.  
  3. int bit_count(int x)
  4. {
  5. int ret = 0;
  6.  
  7. while ( x )
  8. {
  9. ++ret;
  10. x = x & ( x + ( ~1 + 1 ) );
  11. // ~1 + 1 == -1
  12. // x + (-1) == x - 1
  13. }
  14.  
  15. return ret;
  16. }
  17.  
  18. int main(void)
  19. {
  20. int input;
  21.  
  22. if ( scanf("%d", &input) == 1 )
  23. printf("Count of 1 bits: %d\n", bit_count(input));
  24.  
  25. return 0;
  26. }
  27.  
Success #stdin #stdout 0s 4496KB
stdin
100
stdout
Count of 1 bits: 3