#include <iostream>
//this test will output the result and return number of iterations required
int method1( int n ); //simple - bitwise
int method2( int n ); //Kernigan's method
int main() {
int n = 3526; //0110111000110 - 7 bits set
int it1 = method1(n), it2 = method2(n); //iterations required
std::cout << "Iterations required method1: " << it1 << std::endl;
std::cout << "Iterations required method2: " << it2 << std::endl;
return 0;
}
int method1( int n )
{
int count = 0 , i;
for( i = 0; n; ++i )
{
count += n & 1;
n >>= 1;
}
std::cout << "Bits set: " << count << std::endl;
return( i);
}
int method2( int n )
{
int i;
for( i = 0; n; ++i )
{
n &= n - 1;
}
std::cout << "Bits set: " << i << std::endl;
return( i );
}
I2luY2x1ZGUgPGlvc3RyZWFtPgovL3RoaXMgdGVzdCB3aWxsIG91dHB1dCB0aGUgcmVzdWx0IGFuZCByZXR1cm4gbnVtYmVyIG9mIGl0ZXJhdGlvbnMgcmVxdWlyZWQKaW50IG1ldGhvZDEoIGludCBuICk7IC8vc2ltcGxlIC0gYml0d2lzZQppbnQgbWV0aG9kMiggaW50IG4gKTsgLy9LZXJuaWdhbidzIG1ldGhvZAoKaW50IG1haW4oKSB7CglpbnQgbiA9IDM1MjY7IC8vMDExMDExMTAwMDExMCAtIDcgYml0cyBzZXQKCWludCBpdDEgPSBtZXRob2QxKG4pLCBpdDIgPSBtZXRob2QyKG4pOyAvL2l0ZXJhdGlvbnMgcmVxdWlyZWQKCQoJc3RkOjpjb3V0IDw8ICJJdGVyYXRpb25zIHJlcXVpcmVkIG1ldGhvZDE6ICIgPDwgaXQxIDw8IHN0ZDo6ZW5kbDsKCXN0ZDo6Y291dCA8PCAiSXRlcmF0aW9ucyByZXF1aXJlZCBtZXRob2QyOiAiIDw8IGl0MiA8PCBzdGQ6OmVuZGw7CgkKCXJldHVybiAwOwp9CgppbnQgbWV0aG9kMSggaW50IG4gKQp7CglpbnQgY291bnQgPSAwICwgaTsKCWZvciggaSA9IDA7IG47ICsraSApCgl7CgkJY291bnQgKz0gbiAmIDE7CgkJbiA+Pj0gMTsKCX0KCQoJc3RkOjpjb3V0IDw8ICJCaXRzIHNldDogIiA8PCBjb3VudCA8PCBzdGQ6OmVuZGw7CglyZXR1cm4oIGkpOwoJCn0KCmludCBtZXRob2QyKCBpbnQgbiApCnsKCWludCBpOwoJZm9yKCBpID0gMDsgbjsgKytpICkKCXsKCQluICY9IG4gLSAxOwoJfQoJc3RkOjpjb3V0IDw8ICJCaXRzIHNldDogIiA8PCBpIDw8IHN0ZDo6ZW5kbDsKCXJldHVybiggaSApOwp9Cg==