write your own Atoi function
implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it.
Example 1:
Input:
str = 123
Output: 123
Example 2:
Input:
str = 21a
Output: -1
Explanation: Output is -1 as all
characters are not digit only.
c++ implementation with explanation:
int atoi(string str)
{
//Your code here
int result=0; //Stores and returns the integer converted value for str
int i=0; //just a current character pointer for string
int sign = 1; //multiplied at the end to result to determine if the string is +ve or -ve
if(str[i]=='-') //Check the sign of string (+ or -)
{
sign = -1;
i++;
}
//Now traverse the entire string and convert it into integer
while(str[i])
{
//If any character is not an integer then just return -1
if(!(str[i]-'0'>=0 && str[i]-'0'<=9))
return -1;
//else just keep updating the result
result = result*10 + str[i]-'0';
i++;
}
return result*sign;
}
Time Complexity: O(n) ,where n is the length of the string
No comments