Count Set Bits in an Integer

Code

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

int count_set_bits(int8_t reg){
    int count = 0;
    if(reg < 0) return 32; // For negative numbers, all bits are set
    while(reg){
        count += (reg & 1);
        reg >>= 1;
    }
    return count;
}

int main(){
    int8_t reg ;
    scanf("%hhd", &reg);
    printf("%d", count_set_bits(reg));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

2