-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString_To_Integer.cc
68 lines (60 loc) · 1.4 KB
/
String_To_Integer.cc
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
67
68
#include <iostream>
#include <climits>
#include <string.h>
class Solution {
public:
int atoi(const char *str) {
if(str)
{
int ret = 0;
int ret_saved = 0;
const char *p = str;
bool negative = false;
bool overflow = false;
while (*p == ' ' || *p == '\t')
p++;
if(*p == '-')
{
negative = true;
p++;
}
else if(*p == '+')
{
p++;
}
while(*p != '\0')
{
int cur = *p - '0';
if (cur < -9 || cur > 9)
break;
if (negative)
cur = -cur;
ret_saved = ret * 10 + cur;
int check = ret_saved / 10;
if (check != ret && !negative)
{
return INT_MAX;
}
if(check != ret && negative)
{
return INT_MIN;
}
ret = ret_saved;
p++;
}
return ret;
}
}
void test()
{
int ret = atoi(" 10522545459");
std::cout<< ret << std::endl;
ret = atoi("-1");
std::cout<< ret << std::endl;
}
};
int main()
{
Solution s;
s.test();
}