-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.string-to-integer-atoi.cpp
More file actions
83 lines (71 loc) · 1.68 KB
/
8.string-to-integer-atoi.cpp
File metadata and controls
83 lines (71 loc) · 1.68 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "testharness.h"
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int myAtoi(const char* str)
{
if (str == NULL) return 0;
while (isspace(*str))
str++;
bool overflow = false;
bool sign = true;
unsigned int num = 0;
if (*str == '-') {
sign = false;
str++;
} else if (*str == '+') {
str++;
}
const unsigned int OverflowSentry = 2147483648U / 10;
while (isdigit(*str)) {
if (num > OverflowSentry) {
overflow = true;
break;
}
num *= 10;
num += *str - '0';
str++;
}
if (!overflow && num > (2147483648U - (sign ? 1 : 0))) {
overflow = true;
}
if (overflow) {
return sign ? 2147483647 : -2147483648;
} else {
int tmp = num;
return sign ? tmp : -tmp;
}
}
class Solution {
};
struct TestCase {
const char* str;
int num;
};
TEST(Solution, test) {
TestCase cases[] = {
{"-2147483649", -2147483648},
{"-2147483648", -2147483648},
{"-2147483647", -2147483647},
{" 10522545459", 2147483647},
{"2147483647", 2147483647},
{"2147483648", 2147483647},
{"0", 0},
{"01", 1},
{" 1", 1},
{"1 ", 1},
{"b1", 0},
{"+1", 1},
{"+.1", 0},
{"-1", -1},
{"-0", 0},
{"-b3", 0},
{"-99999999999999999999", -2147483648},
{"234b", 234},
{"\t\n-100b", -100}};
for (int i = 0; i < sizeof(cases)/sizeof(cases[0]); i++) {
std::cout << i << ": " << cases[i].str << std::endl;
ASSERT_EQ(cases[i].num, myAtoi(cases[i].str));
}
}