Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    // Your logic here
    uint8_t numbers[50]; 
    int index = 0, num = 0, hun = 1;
    if(str[0]=='-')
    {
        index++;
        while(str[index]>'0' && str[index]<'9')
        {
            numbers[index] = str[index] - '0';
            index++;
        }
        
        for(int i=index-1; i>=0; i--)
        {
            num += numbers[i]*hun;
            hun *= 10;
        }

        return num*(-1);
    }
    else if(str[0]=='+')
    {
        index++;
        while(str[index]>'0' && str[index]<'9')
        {
            numbers[index] = str[index] - '0';
            index++;
        }

        for(int i=index-1; i>=0; i--)
        {
            num += numbers[i]*hun;
            hun *= 10;
        }

        return num;
    }
    else
    {
        while(str[index]>'0' && str[index]<'9')
        {
            numbers[index] = str[index] - '0';
            index++;
        }

        for(int i=index-1; i>=0; i--)
        {
            num += numbers[i]*hun;
            hun *= 10;
        }

        return num;

    }
}

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