All submissions

Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    int val=0;
    int k=0;
    int arr[10];
    int x=1;
    do
    {

        
        if(*str>=48 && *str<=58)
        {
            arr[k]=*str;
            k++;
            
        }
        else if(*str =='-' || *str =='+')
        {
            if(*str =='-')
            {
                x=x*(-1);
            }
        }
        else
        {
            for(int i=0;i<k;i++)
            {
                val=val+(arr[i] -48)*pow(10,k-i-1);
            }
            return val*x;
        }

    }while(*str++!='\0');
    return 0;
}

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

 

 

 

Loading...

Input

123abc

Expected Output

123