All submissions

Convert String to Integer

Code

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

bool is_num(char c){
    return (c >= '0' && c <= '9');
}

bool is_minus(char c){
    return c == '-';
}

int custom_atoi(const char *str) {
    int num = 0;
    bool minus = false;
    int i = 0;
    while (str[i] == ' ') i++;
    if (str[i] == '-') {
        minus = true;
        i++;
    } else if (str[i] == '+') {
        i++;
    }
    if (!is_num(str[i])) return 0;
    while (is_num(str[i])) {
        num = num * 10 + (str[i] - '0');
        i++;
    }
    return minus ? -num : num;
}


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

    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

 

 

 

Loading...

Input

123abc

Expected Output

123