All submissions

Convert Decimal Number to Binary or Hex Without itoa function

Code

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

void print_base(uint16_t num, uint8_t base) {
    
    // Your logic here
 
    int max = 0;

    for(int n = 0 ; n < 16 ; n++)
    {
        max = (((num>>(16-1-n)) & 1) && (max == 0))? 16-n : max;  
        
        if((base == 2) && (max > 0))
        {
            printf("%d",(num>>(16-1-n) & 1));
        }

    }

    if((base == 2) && (max == 0))
    { 
        printf("0"); 
        return;
    }

    int hexwide = (max/4) + (max%4);
    //printf("%d",hexwide);
    if(base == 16)    
    {
        for(int n = 0 ; n < hexwide ; n ++)
        {
            char ch = num>>(4*(1-n)) & 0xF;
            printf("%c",(ch<10)? ch+48 : ch+55);
        }
    }


}

int main() {
    uint16_t num;
    uint8_t base;
    scanf("%hu %hhu", &num, &base);

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

10 2

Expected Output

1010