98. Convert String to Integer

Back To All Submissions
Previous Submission
Next Submission

Code

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

int custom_atoi(const char *str) {
    int index = 0, tail = 0;
    uint8_t negative_flag = 0;
    if(str[index] == '-') {
        negative_flag = 1;
        index++;
        tail = 1;
    } else if(str[index] == '+') { index++; tail = 1; }
    
    while(str[index] != '\0') {
        if(str[index] < '0' || str[index] > '9') break;
        index++;
    }
    int val = 0, mul = 1;
    for(int i = index-1; i >= tail; i--) {
        val += (str[i] - '0') * mul;
        mul *= 10;
    }

    if(negative_flag) val *= -1;
    return val;
}

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

 

 

 

Was this helpful?
Upvote
Downvote