All submissions

Convert Decimal Number to Binary or Hex Without itoa function

Code

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

void print_base(uint16_t num, uint8_t base) 
{
    if(!num)
    {
      printf("0");
      return ;
    }
    char *a=(char *)malloc(17*sizeof(char)); //For 16 bit value including null character.Hence allocated 17 bytes.
    if(!a)
     exit(EXIT_FAILURE);

    char *ptr=&a[17];
    while(num)
    {
       ptr--;
       *ptr="0123456789ABCDEF"[num%base];
       num=num/base;
    }
    printf("%s\n",ptr);
    free(a);
}

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