Also how are you getting the binary number? You could simply set a counter and increment by one when ever you read in a 1.
*edit
Another method would be to shift it right and when ever the right bit is a 1 increment the count by one. But this is probably just as bad as a for loop.
1 2 3 4 5 6
int count = 0;
while( number ) //while any bits are set not sure how you are getting the value
{
count += number & 1;
number >> 1;
}
There is also kernigans method which should be a lot faster than o(n)
#include <iostream>
//this test will output the result and return number of iterations required
int method1( int n ); //simple - bitwise - O(bits) == O(n)
int method2( int n ); //Kernigan's method - O(bitsset) < O(n) not sure exact ratio
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 );
}
Compilers typically provide intrinsics for efficiently counting bits; most modern processors have a population count machine instruction.
The safe, portable, option is to use std::bitset<>::count(); the machine code generated would typically be the most efficient code available on the target hardware architecture.