Convert String to Integer

Code

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

int custom_atoi(const char *str) {
    // Your logic here
    int cnt = 0;
    int cnt_2 =0;
    int retval = 0;
    char switch_t =1;
    while(str[cnt]!=0 && switch_t){
        if(str[cnt]=='-' && str[cnt+1]>='0' && str[cnt+1]<='9'){
                cnt_2 = cnt+1;
                while(str[cnt_2]>='0' && str[cnt_2]<='9'){
                    retval= (retval*10)+ str[cnt_2] - '0';
                    cnt_2++;
                }
                retval = -retval;
                break;
        }
        else if((str[cnt]=='+' && str[cnt+1]>='0' && str[cnt+1]<='9') | (str[cnt]>='0' && str[cnt]<='9')){
            if(str[cnt]=='+'){
                 cnt_2 = cnt+1;
            }
            else{
               cnt_2 = cnt; 
            }
            
                while(str[cnt_2]>='0' && str[cnt_2]<='9'){
                    retval= (retval*10)+ str[cnt_2] - '0';
                    cnt_2++;
                }
                
                break;
        }
        else{
            break;
        }
        cnt++;
    }
    return retval;
}

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