All submissions

Convert String to Integer

 

#include <stdio.h>
#include <stdint.h>
#include <ctype.h>   // for isdigit()

int custom_atoi(const char *str) {
    int result = 0;
    int sign = 1;
    uint8_t index = 0;

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

    // Start reading digits
    while (str[index] >= '0' && str[index] <= '9') 
    {
        result = result * 10 + (str[index] - '0');
        index++;
    }

    return result * sign;
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline if present
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    printf("%d", custom_atoi(str));
    return 0;
}

 

 

 

Loading...

Input

123abc

Expected Output

123