# Leetcode String to Integer (atoi) problem solution in C

Feb 10, 2023

In the Leetcode String to Integer (atoi) problem solution in C programming Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).

The algorithm for myAtoi(string s) is as follows:

Check if the next character (if not already at the end of the string) is ‘-‘ or ‘+’. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.

## Leetcode String to Integer (atoi) problem solution in C programming

``````int myAtoi(char * str){

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

int sign = 1;
long result = 0;

if (*str == '-'){
sign = -1;
str++;
}
else if (*str == '+')
str++;

while ((*str >= '0') && (*str <= '9')) {
result = (result*10) + (*str-'0');

//check limits
if (result * sign < INT_MIN)
return INT_MIN;

if (result * sign > INT_MAX)
return INT_MAX;

str++;
}

return (int)(result * sign);

}``````

#### By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.