C Programming – HackerRank Solution | Binary Equivalent 1 |

(HackerRank) Write a Modular C Programming code to solve Binary Equivalent 1, Find the binary equivalent of a positive integer, Display the binary equivalent of the number

Find the binary equivalent of a positive integer

Input Format

First line contains a positive integer ‘N’

Constraints

N>=0 and N<=(2^31 – 1)

Output Format

Display the binary equivalent of the number

Sample Input 0

5

Sample Output 0

101

Explanation 0

5 in binary is 101

Sample Input 1

-3

Sample Output 1

Invalid

Refer : C Programming HackerRank all solutions for Loops | Arrays | strings

 

CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main() {
    int n,i=0,r;
    int binary[100];
    scanf("%d",&n);
    if(n>=0 && n<=pow(2,31)-1) 
{ 
do 
{ 
r=n%2; 
if(r==0)
 { 
binary[i]=0; 
} 
else
{ 
binary[i]=1; 
} 
i++; 
n=n/2; 
}
while(n!=0); 
for(r=i-1;r>=0;r--)
    {
        printf("%d",binary[r]);
    }
}
    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)

5
Your Output (stdout)

101
Expected Output

101

 

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University

Leave a Comment