mercredi 18 septembre 2019

Character string to int-atoi()

"I am trying to write code for atoi function.MY problem is actual output is not matching with the

expected output for the following case.

Input="7 U 0 T7165 0128862 089 39 5"

Actual output=2147483647

Expected output=7

The following is the link to know problem constraints https://www.interviewbit.com/problems/atoi/"

/function to convert string to int

int atoi(const string A) {

//string to store numeric in string A

  string a;

//b and d store INT_MAX and INT_MIN in string form

 string b=to_string(INT_MAX),d=to_string(INT_MIN);

//loop to store numeric in a

   for(int i=0;i<A.length();i++){

   if(a.length()==0&&A[i]=='-')a.push_back(A[i]);

    if(A[i]==' ')break;

    if(isdigit(A[i]))a.push_back(A[i]);



    }

    if(a.length()==0)return 0;

    else if(a>b)return INT_MAX;
    else if(a<d)return INT_MIN;
   else{      
   int f=0;
   for(int i=0;i<a.size();i++){


       f=f*10+(a[i]-'0');
   }

   return f;
    }

     }

Aucun commentaire:

Enregistrer un commentaire