logo CodeStepByStep logo

countSetBits

Language/Type: C++ bit algorithms

Write a function named countSetBits that accepts as a parameter an integer n and returns the count of the number of 1s in the binary representation of n. For example, if the call is countSetBits(44), the binary representation of 44 is 101100 preceded by 26 zeros, meaning three bits are 1s, so you should return 3.

You should solve this problem using bitwise operators and arithmetic. Do not use any collections or strings to solve the problem. You may assume that an int occupies 32 bits in memory.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.