Start with count = 0

While the integer is not 0

If the integer AND 1 equals 1, increment count

Shift the integer one bit to the right

Return count

 

int numOnesInBinary( int number ) {
int numOnes = 0; while( number != 0 ){
if( ( number & 1 ) == 1 ) numOnes++;
number = number >>> 1; return numOnes;
}
}

Advertisements