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
    char res[16]; 
    char hex[17] ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','\0'};
    // if(base ==2)
    // {
    //     int i=0;
    //     while(num)
    //     {
    //         num%2 ? res|=(1<<i) : res|=(0<<i);
    //         num = num/2;
    //         i++;
    //     }
    //     printf("%b", res);
    // }
    if(num==0)
    {
        printf("0");
        return;
    }
    int i=0;
        while(num)
        {
          res[i]= hex[num%base];
          num=num/base;
          i++;
        }
        while(i)
        {
            printf("%c", res[i-1]);
            i--;
        }
    }


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