Tutorialspoint
Problem
Solution
Submissions

Count Set Bits

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to count the number of '1' bits (set bits) in a 32-bit unsigned integer. This is also known as the Hamming weight of a number.

Example 1
  • Input: n = 11 (represented in binary as 00000000000000000000000000001011)
  • Output: 3
  • Explanation: The binary representation of 11 is 00000000000000000000000000001011. There are three '1' bits in this binary representation at positions 0, 1, and 3. Therefore, the Hamming weight is 3.
Example 2
  • Input: n = 128 (represented in binary as 00000000000000000000000010000000)
  • Output: 1
  • Explanation: The binary representation of 128 is 00000000000000000000000010000000. There is only one '1' bit in this binary representation at position 7. Therefore, the Hamming weight is 1.
Constraints
  • The input must be a 32-bit unsigned integer.
  • You should count all set bits in the entire 32-bit representation.
  • Time Complexity: O(k), where k is the number of set bits in the integer.
  • Space Complexity: O(1), only constant extra space is used.
NumberBitwise OperationsAccentureDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use bit manipulation techniques to count the set bits.
  • Consider using a loop to check each bit position.
  • You can use the bitwise AND operator (&) to check if a bit is set.
  • The n & (n-1) technique removes the rightmost set bit from n in each iteration.
  • Keep iterating until n becomes 0 (no more set bits).
  • This is also known as Brian Kernighan's algorithm.
  • Alternatively, you can use right shift operator (>>) and check the LSB.

Steps to solve by this approach:

 Step 1: Initialize a counter variable to 0 to keep track of the number of set bits.

 Step 2: Loop while the number n is not zero (which means there are still bits to check).
 Step 3: Use bitwise AND operation (n & 1) to check if the least significant bit is 1.
 Step 4: If the least significant bit is 1, increment the counter.
 Step 5: Right shift n by 1 to examine the next bit.
 Step 6: Repeat steps 3-5 until n becomes 0.
 Step 7: Return the final count, which represents the number of set bits in the original number.

Submitted Code :