-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path008_String_to_Integer.cpp
52 lines (51 loc) · 1.42 KB
/
008_String_to_Integer.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
#include<iostream>
#include<climits>
#include<string>
#include<cctype>
using namespace std;
class Solution
{
public:
int myAtoi(string str)
{
int plus = 1;
size_t slen = str.length();
size_t index = str.find_first_not_of(' ');
int64_t sum = 0;
while( index < slen)
{
if( str[index] == '+' || str[index] == '-')
{
plus = str[index] == '-' ? -1 : 1;
++index;
}
//此处加了else,就无法处理 +-2 这样的test case
while(isdigit(str[index]))
{
sum = sum*10+(str[index]-'0');
index++;
//|-2147483647 to +2147483647| <= int_max
//|-infinty to -2147483648| > 2147483647
//|+2147483648 to +infinty| > 2147483647
if(sum > INT_MAX)
return (plus==1) ? INT_MAX: INT_MIN;
}
return sum*plus;
}
return sum;
}
};
int main(int argc, char const *argv[])
{
//-2147483648
//2147483647
Solution sol;
cout<<sol.myAtoi(" 0000000000000 ")<<endl;
cout<<sol.myAtoi("+-2")<<endl;
cout<<sol.myAtoi("0-1")<<endl;
cout<<sol.myAtoi("+2147483648")<<endl;
cout<<sol.myAtoi("-2147483648")<<endl;
cout<<sol.myAtoi("+2147483649")<<endl;
cout<<sol.myAtoi("-2147483649")<<endl;
return 0;
}