-
Notifications
You must be signed in to change notification settings - Fork 0
/
008-StringToInteger(atoi).cpp
62 lines (51 loc) · 1.42 KB
/
008-StringToInteger(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
61
62
//-----------------------------------------------------------------------------
// Runtime: 8ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "008-StringToInteger(atoi).h"
namespace LeetCode
{
_008_StringToInteger::_008_StringToInteger()
{
}
_008_StringToInteger::~_008_StringToInteger()
{
}
int _008_StringToInteger::myAtoi(string str)
{
if (str.empty()) { return 0; }
bool nagative = false;
int index = 0;
while (index < str.size())
{
if (!isspace(str[index])) break;
else index++;
}
if (str[index] == '-')
{
nagative = true;
index++;
}
else if (str[index] == '+')
{
index++;
}
int result = 0, digit;
auto POSITIVE_OVERFLOW_HEAD = INT_MAX / 10;
auto POSITIVE_OVERFLOW_TAIL = INT_MAX % 10;
while (index < str.size() && isdigit(str[index]))
{
digit = str[index] - '0';
if (result > POSITIVE_OVERFLOW_HEAD ||
(result == POSITIVE_OVERFLOW_HEAD && digit > POSITIVE_OVERFLOW_TAIL))
{
return nagative ? INT_MIN : INT_MAX;
}
result = result * 10 + digit;
index++;
}
return nagative ? -result : result;
}
}