Skip to content

Commit 7722437

Browse files
author
JINGUIWANG
committed
add solution
Change-Id: Idbe5c6725a68b1afa0983f8a4444ea7fdd6b1d90
1 parent 20424da commit 7722437

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

StringtoInteger(atoi).h

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/*
22
Author: Annie Kim, [email protected]
33
Date: May 17, 2013
4-
Update: Sep 22, 2013
4+
Update: Dec 14, 2014(By [email protected])
55
Problem: String to Integer (atoi)
66
Difficulty: Easy
7-
Source: http://leetcode.com/onlinejudge#question_8
7+
Source: https://oj.leetcode.com/problems/string-to-integer-atoi/solution/
88
Notes:
99
Implement atoi to convert a string to an integer.
1010
Hint: Carefully consider all possible input cases. If you want a challenge, please do not
@@ -25,12 +25,16 @@
2525
If no valid conversion could be performed, a zero value is returned. If the correct value is out
2626
of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
2727
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..
2933
*/
3034

3135
class Solution {
3236
public:
33-
int atoi(const char *str) {
37+
int atoi_1(const char *str) {
3438
if (!str) return 0;
3539
while (*str == ' ') str++;
3640
bool positive = true;
@@ -48,4 +52,22 @@ class Solution {
4852
if (res < INT_MIN) return INT_MIN;
4953
return (int)res;
5054
}
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+
}
5173
};

0 commit comments

Comments
 (0)