All submissions

Convert String to Integer

Code

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

int custom_atoi(const char *str) 
{
    char flag=1;
    int i=0;
    if(str[i]=='-')
    {
        flag=-1;
        i++;
    }
    
    int ans=0;
    if( (str[0]>=65 && str[0]<=90) || (str[0]>=97 && str[0]<=122))
      return ans;

    char flag2=0;

    //flag2=1 means conversion started. During that time if we encounter any non-numeric character we need to return with current value stored in ans to main function.
    while(str[i])
    {
        if(flag2 && !(str[i]>=48 && str[i]<=57)) 
           break;

        /*
        flag2=1 will be enabled(logic high) after number detection started in below condition. 
        During that time if we found any character which is not a number then we immediately break the loop. 
        */   

        if( (str[i]>=48 && str[i]<=57) ) //once numeric digit is identified we start converting into integer.Flag2 is a variable which tells that conversion is started.
        {
         ans=(ans*10)+(str[i]-'0');
         flag2=1;  //this will help us to tell that we detcted number and started convesion.
        }

         i++;
    }

    return (ans*((int)flag));
}

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