-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path49_StringToInt.cpp
71 lines (58 loc) · 884 Bytes
/
49_StringToInt.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
63
64
65
66
67
68
69
70
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX 100006
bool valid = true;
int StrToInt(char *str)
{
valid = true;
if (str == NULL || *str == '\0')
{
valid = false;
return 0;
}
int num = 0, i;
bool minus = false;
if (*str == '-')
{
minus = true;
str ++;
}
if (*str == '+')
str ++;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
int flag = minus ? -1 : 1;
num = num * 10 + flag * (str[i] - '0');
if ((!minus && num > 0x7fffffff) || (minus && num < 0x80000000))
{
valid = false;
num = 0;
break;
}
}
else
{
valid = false;
num = 0;
break;
}
}
return num;
}
int main(void)
{
char str[MAX];
while (scanf("%s", str) != EOF)
{
int num = StrToInt(str);
if (valid)
printf("%d\n", num);
else
printf("My God\n");
}
return 0;
}