Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    // Your logic here
    uint8_t first = 0;
    uint8_t read = 0;
    int value = 0;
    if(str[first] == '-' || str[first] == '+' )
    {
        read = first + 1;
        while( (str[read]>= 48 && str[read] <=57)&& str[read] !='\0')
        {
            value = value*10 + ((uint8_t)str[read] - 48);
            read++;
        }
        if(str[first ] == '-')
        {
            return value*(-1);
        }
        else return value;
    }
    else if(str[first]>= 48 && str[first] <=57)
    {
        while((str[read]>= 48 && str[read] <=57)&& str[read] !='\0')
        {
            value = value * 10 + ((uint8_t)str[read] - 48);
            read++;
        }
        return value;
    }
    return 0;
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    printf("%d", custom_atoi(str));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

123abc

Expected Output

123