Count Set Bits in an Integer

RohitTelkar
RohitTelkar

Solving Approach:

  1. Input Reading:
    • The program reads an integer n from the user using scanf.
  2. Bitwise AND Operation:
    • Inside the countSetBits function, it checks the least significant bit (LSB) of n using (n & 0x01).
    • If the LSB is 1, it adds 1 to the count.
  3. Bit Shifting:
    • The number n is right-shifted by one position using n = n >> 1 to process the next bit in the next loop iteration.
  4. Loop Until Zero:
    • The loop continues until all bits have been processed (i.e., n becomes 0).
  5. Output:
    • After counting all set bits, the result is printed using printf.

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    int count = 0;
    while(n){
        count = count + (n & 0x01);
        n = n >> 1;
    }
    return count;
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%d\n", countSetBits(n));
    return 0;
}
Loading...

Input

5

Expected Output

2