Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    int num = 0;
    int sign = 1;
    int index = 0;
    int stop = 0;
    const char offset = '0';

    while (!stop) {
        char ch = str[index];
        if (ch == '\0') {
            // end of string reached
            stop = 1;
        } else if (ch == '+') {
            if (index > 0) {
                // + found not at beginning
                stop = 1;
            }
        } else if (ch == '-') {
            if (index > 0) {
                // - found not at beginning
                stop = 1;
            } else {
                // - found at beginning
                sign = -1;
            }
        } else if (ch >= '0' && ch <= '9') {
            // digit found
            num = num * 10 + (ch - offset);
        } else {
            // other char found
            stop = 1;
        }

        index++;
    }
    return num * sign;
}

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