(HackerRank) Write a Modular C Programming code to solve Set Bits 3, Find the number of set bits (number of 1’s) in binary representation of a given positive number.
Find the number of set bits (number of 1’s) in binary representation of a given positive number.
Input Format
First Line contains a positive integer ‘N’
Constraints
N>0 and N<=(2^31 -1)
Output Format
Output the number of set bits in a single line.
Sample Input 0
-3
Sample Output 0
Invalid
Sample Input 1
9
Sample Output 1
2
Explanation 1
9 in binary is 1001 and number of 1's in 1001 is 2.
CODE:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int main() { int bset=0,i=0; int n,r; scanf("%d",&n); if(n>0) { while(n!=0) { r=n%2; if(r==1) bset++; n=n/2; i++; } printf("%d",bset); } else{ printf("Invalid"); } return 0; }
OUTPUT
Congratulations, you passed the sample test case. Click the Submit Code button to run your code against all the test cases. Input (stdin) -3 Your Output (stdout) Invalid Expected Output Invalid
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University