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) {
    // Your logic here
    // Only handle first string of ints
    // Therefore
    // 1. Handle optional sign
    // 2. Start reading from the first digit until first non-digit
    int i=0;
    int cur_val=0;
    int sign = 1;

    //1. Handle optional signage (increment index)
    if(str[i] == '-'){
        sign = -1;
        i++;
    }
    else if(str[i] == '+'){
        i++;
    }

    //2. Read from first instance of digit until non-digit
    while(str[i] >= '0' && str[i] <='9'){
            //Convert ASCII to int
            //*10 adds a digit
            //+ str - 48 converts ASCII val to int digit
            cur_val = (cur_val *10)  + (str[i] - 48);
            i++;
        }
        return cur_val*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

 

 

 

Was this helpful?
Upvote
Downvote