fork(6) download
  1. #include <iostream>
  2. //this test will output the result and return number of iterations required
  3. int method1( int n ); //simple - bitwise
  4. int method2( int n ); //Kernigan's method
  5.  
  6. int main() {
  7. int n = 3526; //0110111000110 - 7 bits set
  8. int it1 = method1(n), it2 = method2(n); //iterations required
  9.  
  10. std::cout << "Iterations required method1: " << it1 << std::endl;
  11. std::cout << "Iterations required method2: " << it2 << std::endl;
  12.  
  13. return 0;
  14. }
  15.  
  16. int method1( int n )
  17. {
  18. int count = 0 , i;
  19. for( i = 0; n; ++i )
  20. {
  21. count += n & 1;
  22. n >>= 1;
  23. }
  24.  
  25. std::cout << "Bits set: " << count << std::endl;
  26. return( i);
  27.  
  28. }
  29.  
  30. int method2( int n )
  31. {
  32. int i;
  33. for( i = 0; n; ++i )
  34. {
  35. n &= n - 1;
  36. }
  37. std::cout << "Bits set: " << i << std::endl;
  38. return( i );
  39. }
  40.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
Bits set: 7
Bits set: 7
Iterations required method1: 12
Iterations required method2: 7