(HackerRank) Write a Modular C Programming code to solve DECIMAL TO BINARY, He wants to now utilize stack for converting a number from decimal to binary form.
Silversten is fond of converting numbers from one form to another. He has worked on coverting decimal to binary, decimal to octal and vice versa.
He wants to now utilize stack for converting a number from decimal to binary form.
Help Silversten to solve his problem.
Input Format
An integer number in decimal form.
Constraints
Number should be greater than 0.
Output Format
Number in binary form.
Sample Input 0
1
Sample Output 0
1
Sample Input 1
0
Sample Output 1
Number should be greater than 0.
Sample Input 2
99
Sample Output 2
1100011
CODE:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define MAX 50 int isEmpty(int top, int stack_arr[]); void push(int x, int *top, int stack_arr[]); int pop(int *top, int stack_arr[]); void DecToBin(int num); int main() { int num; scanf("%d",&num); if(num==0){ printf("Number should be greater than 0."); } DecToBin(num); return 0; } void DecToBin(int num) { int stack[MAX], top=-1, rem; while(num!=0) { rem = num%2; push(rem, &top, stack); num/=2; } while(top!=-1) printf("%d", pop(&top, stack)); printf("\n"); } void push(int x, int *top, int stack_arr[]) { if(*top == (MAX-1)) printf("Stack Overflow\n"); else { *top=*top+1; stack_arr[*top] = x; } }/*End of push()*/ int pop(int *top, int stack_arr[]) { int x; if(*top == -1) { printf("Stack Underflow\n"); exit(1); } else { x = stack_arr[*top]; *top=*top-1; } return x; }
OUTPUT
Congratulations, you passed the sample test case.
Click the Submit Code button to run your code against all the test cases.
Input (stdin)
1
Your Output (stdout)
1
Expected Output
1
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: