-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement_Atoi.cpp
60 lines (52 loc) · 1.29 KB
/
Implement_Atoi.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
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
/*You are required to complete this method */
int atoi(string s) {
//Your code here
// Check if the string is empty
if (s.empty()) {
return -1;
}
// Initialize result and sign
int result = 0;
int sign = 1;
// Initialize index to start from the first character
int i = 0;
// Check for the sign character
if (s[0] == '-') {
sign = -1;
i++;
}
// Iterate through the string and convert to integer
while (i < s.length()) {
// Check if the character is numeric
if (isdigit(s[i])) {
// Convert character to integer and add to result
result = result * 10 + (s[i] - '0');
i++;
} else {
// If a non-numeric character is encountered, return -1
return -1;
}
}
// Multiply the result by the sign to get the final result
return sign * result;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
Solution ob;
cout<<ob.atoi(s)<<endl;
}
}