98. Convert String to Integer

Back To All Submissions
Previous Submission
Next Submission

Code

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

#define MAX_DIGITS 10

int custom_atoi(const char *str) {
    // Your logic here
    bool mySign = true;     //assume positive number
    bool nonNumeric = false;
    int myIndex = 0;
    int myResult[MAX_DIGITS];
    int8_t myReturnValue = 0;
    uint8_t myOnes = 0;
    uint8_t myTens = 0;
    uint8_t myHundreds = 0;
    int decades = 0;

    while ((*str != 0x00) && nonNumeric == false){
        if (*str == '-') {
            mySign = false;  // number is defined as negative
            str++;          //skip to next value
        }
        else if (*str == '+') {
            mySign = true;  // number is defined as positive
            str++;          //skip to next value
        }

        if (!((*str >= 0x30) && (*str <= 0x39))) {
            nonNumeric = true;  //check for invalid character
            break;
        }
        
        myResult[myIndex++] = (*str - 0x30);
        decades++;
        str++;      
    }

    switch(decades ){
        case 1:
            myHundreds = 0;
            myTens = 0;
            myOnes = myResult[0];                 
            break;

        case 2:
            myHundreds = 0;
            myTens = myResult[0]; 
            myOnes = myResult[1]; 
            break;

        case 3:
            myHundreds = myResult[0]; 
            myTens = myResult[1]; 
            myOnes = myResult[2]; 
            break;

        default:
            break;
    }

    myReturnValue = ((myHundreds * 100) + (myTens * 10) + myOnes);

    if(mySign == false) myReturnValue = -myReturnValue;

    return myReturnValue;
}

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

 

 

 

Was this helpful?
Upvote
Downvote