Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    int i=0;
    bool strFound=false;
    int debStr=0;
    int endStr=0;
    int result = 0;
    while(str[i]!='\0'){
        if((str[i]<='0' || str[i]>='9')&&(str[i]!='-')&&(str[i]!='+')){
            break;
        } 
        else{
            if(!strFound){
                strFound = true;
                debStr = i;
            }
            else{
                endStr = i;
            }   
        }
        i++;
    }
    if(strFound){
        int pow=1;
        for(int j=endStr;j>=debStr;j--){
            if(str[j] == '-') result *= -1;
            else if(str[j] == '+') result *= 1;
            else result += (str[j]-'0')*pow;
            pow*=10;
        }
    }
    
    return result;
}

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