Count Set Bits in an 8-bit Register

Code

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

uint8_t count_set_bits(uint8_t reg) {
    int count = 0;
    while (reg) {
        count += (reg & 1);
        reg >>= 1;
    }
    return count;
}

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

Solving Approach

  • Initialize count = 0.
  • While reg is not zero:
    • Add 1 to count if the last bit (reg & 1) is set.
    • Right shift reg by 1 to check the next bit.
  • Repeat until all bits are checked.
  • Return the total count of set (1) bits.

 

 

Upvote
Downvote
Loading...

Input

0

Expected Output

0