jayati

Implement Atoi

Sep 21st, 2023
1,123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial template for C++
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. // } Driver Code Ends
  8. //User function template for C++
  9.  
  10. class Solution{
  11.   public:
  12.     /*You are required to complete this method */
  13.     int atoi(string str) {
  14.         //Your code here
  15.         int ans=0;
  16.         bool f=true;
  17.         bool isneg=false;
  18.         if(str[0]=='-')
  19.         {
  20.             isneg=true;
  21.         }
  22.         int k=0;
  23.         for(char c:str)
  24.         {
  25.             if(c=='-' && k==0)
  26.             {
  27.                
  28.             }
  29.             else if(c>='0' && c<='9')
  30.             {
  31.                 ans=ans*10+(c-'0');
  32.             }
  33.             else
  34.             {
  35.                 f=false;
  36.                 break;
  37.             }
  38.             k++;
  39.         }
  40.         if(f)
  41.         {
  42.             if(isneg)
  43.             {
  44.                 ans=-1*ans;
  45.             }
  46.             return ans;
  47.         }
  48.         else
  49.         {
  50.             return -1;
  51.         }
  52.     }
  53. };
  54.  
  55. //{ Driver Code Starts.
  56. int main()
  57. {
  58.     int t;
  59.     cin>>t;
  60.     while(t--)
  61.     {
  62.         string s;
  63.         cin>>s;
  64.         Solution ob;
  65.         cout<<ob.atoi(s)<<endl;
  66.     }
  67. }
  68. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment