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) {
    char arr[17];
    int index = 0;
    
    if (num == 0) { 
        printf("0");
        return;
    }
    
    while(num != 0){
    uint8_t remainder = num % base;

    //Case 1 :- If the remainder is less than 10
    if(remainder < 10) arr[index] = '0' + remainder;

    //Case 2 :- If the remainder is more than 10
    else arr[index] = 'A' + (remainder - 10);

    num /= base;
    index++;
    }

    for(int j = index - 1; j >= 0; j--)
    printf("%c", arr[j]);
    
}

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