Implement Atoi

PROBLEM :
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.

Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains a string str .

Output:
For each test case in a new line output will be an integer denoting the converted integer, if the input string is not a numerical string then output will be -1.

Constraints:
1<=T<=100
1<=length of (s,x)<=10

Example(To be used only for expected output) :

Input:
2
123
21a

Output:
123
-1


--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*You are required to complete this method */
int atoi(string str)
{
    int len,i,no ;
    len=str.length() ;
    no=0 ;
    bool flag=false ;
   
    for(i=0;i<len;i++)
    {
        if(str[i]=='-')
            flag=true ;
        else if(!(str[i]-'0'>=0&&str[i]-'0'<=9))
            return -1 ;
        else
            no=no*10+str[i]-'0' ;
    }
    if(flag)
        return -1*no ;
    return no ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )