Bit Counter
C
Medium
4 views
Problem Description
Count the number of 1 bits in an integer using bitwise operators. Use the & operator in a loop and right shift it.
Official Solution
#include <stdio.h>
int main() {
unsigned int n;
int count = 0;
printf("Enter an integer: ");
scanf("%u", &n);
while (n > 0) {
if (n & 1) { // check least significant bit
count++;
}
n = n >> 1; // right shift by 1 bit
}
printf("Number of 1 bits = %dn", count);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!