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) {
    if (base == 2) {
        /*BINARY Format*/
        int started = 0; // flag to avoid leading zeros
        for (int i = 15; i >= 0; i--) {
            int bit = (num >> i) & 1;
            if (bit) started = 1;
            if (started || i == 0) {
                printf("%d", bit);
            }
        }
    } else 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

 

 

 

Loading...

Input

10 2

Expected Output

1010