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
    if (num == 0){
        printf("0");
        return;
    }
    int n = (num <= 0xF) ? 4 : 8;
    for (int i = n - 1; i >= 0; i--){
        if (base == 2){
            putchar((num & (1<<i)) ? '1' : '0');
        }
    }
    if (base == 16) {
        printf("%X",num);
    }
}

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

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 2

Expected Output

1010