All submissions

Convert String to Integer

Code

#include <stdio.h>
#include <stdint.h>
#define isNumber(x) (x>=48) && (x<58) 
int custom_atoi(const char *str) 
{
    int mul = 0; 
    const char *start = NULL;
    const char *end = NULL;
    int v = 0;
    int len = 0;
    int Fraction = 0 ; 
    Fraction = (*str == '-')?  -1 : Fraction ;
    Fraction = (*str == '+')?   1 : Fraction ;
    start = (Fraction != 0)? (str+1) : str ;
    end = start ;
    // Your logic here
    while(isNumber(*end) && (*end != NULL))
    {
        end++;
    }

    len = end-start;
    if(len == 0 ) return 0 ;

    for(int n = 0 ; n < len ; n++)
    {
            mul = 1;
            for(int p=0;p<n;p++)
            {
                mul *= 10;
            }
        
            v += (*(start+len-n-1) - 48) * mul;

    }

    if(Fraction == - 1)
        return v * Fraction; 
 
    return  v;
}

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