All submissions

Convert Decimal Number to Binary or Hex Without itoa function

Code

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

char cnvrt_to_ascii(uint8_t num){
    char ch;
    if(num<=9){
        ch = '0'+num;
    }else{
        ch = 'A'+num-10;
    }
    return ch;
}
void strrev(char *str,uint8_t len){
    int i = 0,j=len-1;
    while(i<j){
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++;j--;
    }
}

void print_base(uint16_t num, uint8_t base) {
    // Your logic here
    uint8_t i = 0;
    char str[16] = "0";
    if(num != 0){
        while(num != 0){
            uint8_t digit = num%base;
            str[i++] = cnvrt_to_ascii(digit);
            num = num/base;
        }
        str[i] = '\0';
        strrev(str,i);
    }
    printf("%s",str);
}

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