1
1
/*
2
2
Author: Annie Kim, [email protected]
3
3
Date: May 17, 2013
4
- Update: Sep 22, 2013
4
+ Update: Dec 14, 2014(By [email protected] )
5
5
Problem: String to Integer (atoi)
6
6
Difficulty: Easy
7
- Source: http ://leetcode.com/onlinejudge#question_8
7
+ Source: https ://oj. leetcode.com/problems/string-to-integer-atoi/solution/
8
8
Notes:
9
9
Implement atoi to convert a string to an integer.
10
10
Hint: Carefully consider all possible input cases. If you want a challenge, please do not
25
25
If no valid conversion could be performed, a zero value is returned. If the correct value is out
26
26
of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
27
27
28
- Solution: ...
28
+ Solution: 1. use long type to store the result to deal with overflow.
29
+ 2. To deal with overflow, inspect the current number before multiplication.
30
+ If the current number is greater than 214748364, we know it is going to overflow.
31
+ On the other hand, if the current number is equal to 214748364,
32
+ we know that it will overflow only when the current digit is greater than or equal to 8..
29
33
*/
30
34
31
35
class Solution {
32
36
public:
33
- int atoi (const char *str) {
37
+ int atoi_1 (const char *str) {
34
38
if (!str) return 0 ;
35
39
while (*str == ' ' ) str++;
36
40
bool positive = true ;
@@ -48,4 +52,22 @@ class Solution {
48
52
if (res < INT_MIN) return INT_MIN;
49
53
return (int )res;
50
54
}
55
+ int atoi_2 (const char *str) {
56
+ if (str == NULL ) return 0 ;
57
+ int res = 0 ;
58
+ bool sign = true ;
59
+ while (*str == ' ' ) str++;
60
+ if (*str == ' +' || *str == ' -' ) {
61
+ sign = *str == ' +' ;
62
+ str++;
63
+ }
64
+ while (isdigit (*str)) {
65
+ if (res > INT_MAX/10 || (res == INT_MAX / 10 && *str - ' 0' > INT_MAX % 10 )){
66
+ return sign ? INT_MAX : INT_MIN;
67
+ }
68
+ res = res * 10 + *str - ' 0' ;
69
+ str++;
70
+ }
71
+ return sign ? res : -res;
72
+ }
51
73
};
0 commit comments