All submissions

Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

#include <stdio.h>
#include <stdint.h>
int pow(int x,int y){
    int z=1;
    if(y==0){
        return 1;
    }
    else{
        for(int i=0;i<y;i++){
            z*=x;
        }
        return z;
    }
}
uint16_t hex_to_uint(const char *str) {
    // Your logic here
    int decimal=0,count=0,len=0;
    while(*str!='\0'){
        str++;
        len+=1;
    }
    str--;
    int track=0;
    while(track<len){
        int op=*str;
        if(op=='a'||op=='A'){
            op=10;
        }
        else if(op=='b' || op=='B'){
            op=11;
        }
        else if(op=='c'|| op=='C'){
            op=12;
        }
        else if(op=='d'||op=='D'){
            op=13;
        }
        else if(op=='e' || op=='E'){
            op=14;
        }
        else if(op=='f' || op=='F'){
            op=15;
        }
        else{
            op=(op-'1')+1;
        }
        decimal+=op*(pow(16,count));
        str--;
        track+=1;
        count+=1;
    }
    return decimal;
}

int main() {
    char hex[10];
    scanf("%s", hex);

    printf("%u", hex_to_uint(hex));
    return 0;
}

Solving Approach

 

 

simple looping ,string and pointer concepts helped me  to solve the problem

Loading...

Input

1A3F

Expected Output

6719