-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08.cpp
More file actions
66 lines (52 loc) · 1.02 KB
/
Copy path08.cpp
File metadata and controls
66 lines (52 loc) · 1.02 KB
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
61
62
63
64
65
66
#include<bits/stdc++.h>
#include<String.h>
#include<iostream>
using namespace std;
std::string& trim(std::string &);
int myAtoi(string str) {
if (str == "" || str.size() < 1)
return 0;
// trim white spaces
str = trim(str);
char flag = '+';
// check negative or positive
int i = 0;
if (str[0] == '-') {
flag = '-';
i++;
} else if (str[0] == '+') {
i++;
}
// use double to store result
double result = 0;
// calculate value
while (str.size() > i && str[i] >= '0' && str[i] <= '9') {
result = result * 10 + (str[i] - '0');
i++;
}
if (flag == '-')
result = -result;
// handle max and min
if (result > INT_MAX)
return INT_MAX;
if (result < INT_MIN)
return INT_MIN;
return (int) result;
}
std::string& trim(std::string &s)
{
if (s.empty())
{
return s;
}
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
int main()
{
string s;
cin>>s;
cout<<myAtoi(s)<<endl;
cout<<"hello";
}