98. Convert String to Integer

Back To All Submissions
Previous Submission
Next Submission

Code

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

int custom_atoi(const char *str) {
    // Your logic here
    char cur;
    int length=0;
    int buffer[100];
    bool positive = true;
    for (int i = 0; str[i] != '\0'; ++i) {
        cur = str[i];
        if (i == 0 && (cur == '+' || cur == '-')) {
            if (cur == '-') {positive = false;}
        }

        if (cur >= '0' && cur <= '9') {
            cur -= 48;
            buffer[length] = cur;
            ++length;
        }

        else if (length > 0 || i > 1) {
            break;
        }
    }
    int tens = 1;
    int sum = 0;
    for(int i = length-1; i >= 0; --i) {
        sum += buffer[i] * tens;
        tens *= 10;
    }
    if (!positive) {
        sum *= -1;
    }


    return sum;
}

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