Convert String to Integer

Code

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

int power(int num, int exp)
{
    int result = 1;
    while(exp--)
    {
        result *= num;
    }
    return result;
}
int custom_atoi(const char *str) {
    // Your logic here
    int len = -1;
    while(str[++len] != '\0');

    int temp[255] = {0};
    int count = 0;
    bool negative = false;
    int exp = 0;
    int num = 0;
    for(int i=0; i<len; ++i)
    {
        if((str[i] >= '0') && (str[i] <= '9'))
        {
            temp[count++] = str[i] - '0';
        }
        else if(str[i] == '+')
        {
            continue;
        }
        else if(str[i] == '-')
        {
            negative = true;
        }
        else
        {
            break;
        }
    }

    if(count)
    {
        for(int i=(count-1); i>= 0; --i)
        {
            num += temp[i]*power(10,exp);
            exp++;
        }
        if(negative)
        {
            num = ~(num)+1;
        }
    }
    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