#include <stdio.h>
#include <stdint.h>
/*
Count set bits
countSetBits ->api which takes in a positive integer (assumption)
Input: 5 (0101)
Output: 2
Plan:
- Keep shifting to the right and & with 1U (do this a while loop)
- increment a count var if 1 is encountered
- return the count
Edge cases
- can the number be negative
- what happens when 0 is entered
- uint32 is the upper limit
*/
int countSetBits(unsigned int n) {
// Write your code here
if(n == 0) return 0;
uint8_t countOnes = 0;
while(n)
{
if(n & 1U != 0) countOnes++;
n = n >> 1U;
}
return countOnes;
}
int main() {
int n;
scanf("%d", &n);
printf("%d", countSetBits(n));
return 0;
}
Input
5
Expected Output
2