Convert String to Integer

Code

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

bool is_digit(char str) {
    return ((str >= '0') && (str <= '9'))? 1 : 0 ;
}

int custom_atoi(const char *str) {
    int i = 0;
    bool flag_negative = 0;
    if((str[0] == '-')) i = flag_negative = 1;
    else if((str[0] == '+')) i = 1;
    else if(!is_digit(str[0])) return 0;

    uint8_t value = 0;
    while (str[i]) {
        if(!is_digit(str[i])) break;
        value = (value * 10) + (uint8_t)(str[i] - '0');
        i++;
    }
    return flag_negative ? 0 - value : value;
}

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