All submissions

Print Binary Representation of an 8-bit or 16-bit Value

Code

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

void print_binary(uint16_t val) {
    // Your logic here
    if(val<=255){
        int arr[8];
        int index=0;
        while(val>0){
            int y=val%2;
            arr[index]=y;
            val/=2;
            index+=1;
        }
        if(index<8){
            int count=8-index;
            while(count>0){
                arr[index]=0;
                index+=1;
                count--;
            }
        }
        for(int i=index-1;i>=0;i--){
            printf("%d",arr[i]);
        }
    }
    else{
        int arr[16];
        int index=0;
        while(val>0){
            int y=val%2;
            arr[index]=y;
            val/=2;
            index+=1;
        }
        if(index<16){
            int count=16-index;
            while(count>0){
                arr[index]=0;
                index+=1;
                count--;
            }
        }
        for(int i=index-1;i>=0;i--){
            printf("%d",arr[i]);
        }
    }
 
}

int main() {
    uint16_t val;
    scanf("%hu", &val);
    print_binary(val);
    return 0;
}

Solving Approach

simple looping and decimal to binary concepts helped me to solve the problem

 

 

Loading...

Input

10

Expected Output

00001010