Convert String to Integer

Code

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

int pow(int n, int i){
    if (i <= 0){
        return 1;
    }
    while(i-1){
        n = n * n;
        i--;
    }
    return n;
}

int custom_atoi(const char *str) {
    bool is_neg = false;
    int num_list[255];
    int size = 0;
    for (size_t i=0; i,255; i++){
        char chr = *(str+i);
        if (chr == '-' & i==0){
            is_neg = true;
        } else if  (chr == '+' & i==0){
            continue;
        } else if ((chr >= '0') & (chr <= '9')){
            int num = ((int)chr) - 48;
            num_list[size] = num;
            size++; 
        } else {
            break;
        }
    }

    int result = 0;
    for (size_t i=0; i<size; i++){
        int number = num_list[i] * pow(10, (size-i)-1);
        result += number;
    }
    if (is_neg) {
        result *= -1;
    }
    return result;
}

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