-
Notifications
You must be signed in to change notification settings - Fork 161
/
string-to-integer-atoi.md
56 lines (40 loc) · 2.66 KB
/
string-to-integer-atoi.md
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
<p>Implement <code><span>atoi</span></code> which converts a string to an integer.</p>
<p>The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.</p>
<p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.</p>
<p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.</p>
<p>If no valid conversion could be performed, a zero value is returned.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Only the space character <code>' '</code> is considered as whitespace character.</li>
<li>Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>, 2<sup>31 </sup>− 1]. If the numerical value is out of the range of representable values, INT_MAX (2<sup>31 </sup>− 1) or INT_MIN (−2<sup>31</sup>) is returned.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> "42"
<strong>Output:</strong> 42
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> " -42"
<strong>Output:</strong> -42
<strong>Explanation:</strong> The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.
</pre>
<p><strong>Example 3:</strong></p>
<pre>
<strong>Input:</strong> "4193 with words"
<strong>Output:</strong> 4193
<strong>Explanation:</strong> Conversion stops at digit '3' as the next character is not a numerical digit.
</pre>
<p><strong>Example 4:</strong></p>
<pre>
<strong>Input:</strong> "words and 987"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.</pre>
<p><strong>Example 5:</strong></p>
<pre>
<strong>Input:</strong> "-91283472332"
<strong>Output:</strong> -2147483648
<strong>Explanation:</strong> The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−2<sup>31</sup>) is returned.</pre>