Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    // Your logic here
    int logic = 1;
    int index = 0;
    int res = 0;
    if(str[0] == '-')
    {
        logic = -1;
        index = 1;
    }
    if(str[0] == '+')
    {
        logic = 1;
        index = 1;
    }

    while(str[index] != '\0')
    {
        if((str[index] >='0') && (str[index] <= '9'))
        {
            res = res*10 + (str[index] - '0');
        }
        else
        {
            break;
        }
        index++;
    }


    // if(logic == 0)
    // {
        return res*(logic);
    // }

    // return res;
}

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