-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.cpp
More file actions
69 lines (61 loc) · 1.52 KB
/
atoi.cpp
File metadata and controls
69 lines (61 loc) · 1.52 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
67
68
69
// 8. String to Integer (atoi)b)
// Author: xianfeng.zhu@gmail.com
#include <ctype.h>
#include <stdio.h>
#include <limits.h>
#include <string>
class Solution
{
public:
int myAtoi(const std::string& str)
{
int num = 0;
int idx = 0;
// Ignore whitespace character
while (idx < str.size() && str[idx] == ' ')
{
idx++;
}
if (idx == str.size())
{
return 0;
}
// Determine minus sign
bool minus = false;
if (str[idx] == '-' || str[idx] == '+')
{
minus = (str[idx] == '-' ? true : false);
idx++;
}
while (idx < str.size() && isdigit(str[idx]) != 0)
{
int digit = str[idx] - '0';
digit *= (minus ? -1 : 1);
if ((num > INT_MAX / 10) || (num == INT_MAX / 10 && digit >= INT_MAX % 10))
{
// Overflow, bigger than INT_MAX
return INT_MAX;
}
if ((num < INT_MIN / 10) || (num == INT_MIN / 10 && digit <= INT_MIN % 10))
{
// Overflow, smaller than INT_MIN
return INT_MIN;
}
num = num * 10 + digit;
idx++;
}
return num;
}
};
int main(int argc, char* argv[])
{
std::string str = "-91283472332";
if (argc > 1)
{
str = argv[1];
}
int num = Solution().myAtoi(str);
printf("Input: %s\n", str.c_str());
printf("Output: %d\n", num);
return 0;
}