Implement Atoi | Practice | GeeksforGeeks

Your task  is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it.
Note: You are not allowed to use inbuilt function.
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.

Your Task:
Complete the function atoi() which takes a string as input parameter and returns integer value of it. if the input string is not a numerical string then returns -1.
Note: Numerical strings are the string where either every character is in between 0-9 or where the first character is '-' and the rest all characters are in between 0-9.
Expected Time Complexity: O(|S|), |S| = length of string str.
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ length of S ≤ 10


Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
+1
kumharashvin2043 days ago
//Easy solution c++
if(str.size()==0)return 0;       int i =0;       int sign = +1;       long ans = 0;       if(str[0]=='-'){         sign = -1;         i++;       }              while(i<str.length()){           if(!isdigit(str[i]))return -1;                      ans = ans *10+ str[i]-'0';           i++;       }       return ans*sign;
 
0
wolfofsv4 days ago
Simple Solution
    int atoi(string str) {
        //Your code here
        int ans = 0, factor = 1;
        if(str[0] == '-'){
            factor = -1;
            str[0] = '0';
        }

        for(auto c : str){
            if(c > '9' || c < '0'){
                return -1;
            }
            ans *= 10;
            ans += c - '0';
        }
        return factor*ans;
    }
};

0
rohankundu8595 days ago
//C++ Solution
 
    int atoi(string str)    {       //Your code here       int result=0;       int i=0;              bool flag=false;              if(str[0]=='-')       {           flag=true;           i=1;       }              while(i<str.size())       {           if(str[i]>='0' && str[i]<='9')           {               result=result*10+(str[i]-'0');               i++;           }           else           {               return -1;           }       }              if(flag)       {           return -result;       }       else       {           return result;       }   }
0
ashayvsant6 days ago
class Solution
{
    int atoi(String str) {
    	// Your code here
	    int result = 0;
	    int n = str.length();
	    int place = 0;
	    boolean isNegative = false;
	    int end = 0;
	    
	    if(str.charAt(0) == '-') {
	        isNegative=true;
	        end = 1;
	    }
	    
	    for(int i=n-1; i>=end; i--) {
	        //System.out.println((int)Math.pow(10,place)*(int)(str.charAt(i)-'0'));
	        if(str.charAt(i)-'0' < 0 || str.charAt(i)-'0' > 9) return -1;
	        result = result + (int)Math.pow(10,place)*(int)(str.charAt(i)-'0');      
	        place++;
	    }
	    
	    return isNegative ? -1*result : result;
    }
}
Java Solution
0
rohitasrani20181 week ago
JAVA SOLUTION
 
 
int atoi(String str) {// Your code herechar ch='\0';if(str.charAt(0)=='-' ){    ch=str.charAt(0);    str=str.substring(1,str.length() );    }for(int i=0 ;i<str.length();i++ ){    if(!(str.charAt(i)>='0' && str.charAt(i)<='9') )    {        return -1;    }}return ch=='\0'? Integer.parseInt(str) : -Integer.parseInt(str) ;   }
0
visitant1 week ago
int atoi(string str) {
        //Your code here 52->0 61->9
        int ret = 0;
        int neg = 0;
        for(int i=0; i< str.length(); i++)
        {
            char val = str[i];
            if(val == '-')
            {
                if(neg == 1)
                {
                    neg=0;
                    ret = -1;
                    break;
                }
                neg = 1;
            }
            else if(val > '9' || val < '0')
            {
                neg = 0;
                ret = -1; 
                break;
            }
            else
            {
                // printf("val is %d, %d", val, val-'0');
                ret = ret*10 + ((int)(val-'0'));
            }
        }
        if (neg==1)
        {
            return ret*-1;
        }
        return ret;
    }
0
jay12501 week ago
#easy python code
def atoi(self,string):       # Code here       try:           return int(string)       except:           return -1
0
abhishekvicky123452 weeks ago
class Solution{   int atoi(String str) {   int value=0;   try {   value = Integer.parseInt(str);} catch (NumberFormatException e) {   return -1;}       return value ;    }}   
0
akashmarkad22102 weeks ago
JAVA Solution
 
int atoi(String str) {// Your code here    try    {        int ans = Integer.parseInt(str);        return ans;        }    catch(Exception e)    {        return -1;    }   } 
0
suprithsk20012 weeks ago
//easy python code
val=len(string)       count=0       for i in range (val):           if(string[i].isdigit()or string[i]=='-'):               count=count+1              if(count==val and string.count("-")<=1):           return int(string)       else:           return -1
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.