-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementAtoi.cpp
51 lines (44 loc) · 1.03 KB
/
ImplementAtoi.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Implement Atoi
// 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.
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
/*You are required to complete this method */
int atoi(string str)
{
//Your code here
int num = 0;
bool isNegative = false;
int i = 0;
if(str[i] == '-'){
isNegative = true;
i++;
}
for(; i < str.size(); i++){
if(isdigit(str[i])){
num = num * 10 + (str[i] - '0');
}
else{
return -1;
}
}
return (isNegative == true) ? -num : num;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
Solution ob;
cout<<ob.atoi(s)<<endl;
}
} // } Driver Code Ends