20. Count Set Bits in an 8-bit Register

#include <stdio.h>
#include <stdint.h>

uint8_t count_set_bits(uint8_t reg) {
    uint8_t count = 0;
    while (reg) {
        count += reg & 1;   // Add 1 if LSB is set
        reg >>= 1;          // Shift right
    }
    return count;
}

int main() {
    uint8_t reg;
    scanf("%hhu", &reg);
    printf("%u", count_set_bits(reg));
    return 0;
}

 

Loop through all 8 bits using right shift. At each step, check LSB and increment the count.

 

Loading...

Input

0

Expected Output

0