30. Count Set Bits in an Integer

Back To All Submissions
Previous Submission
Next Submission

Code

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

int count(int n) {
	int cnt = 0;
	unsigned int un = (unsigned int)(n);
	while (un>0) {
		cnt = (un & 0x01) ? (cnt + 1) : cnt;
		un >>= 1;
	}
	return cnt;
}

int main() {
	int n; 
	scanf("%d", &n);
	printf("%d", count(n));
	
	
	
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote