[LeetCode] String to Integer (atoi)

8. String to Integer (atoi)

Implement atoi which converts a string to an integer.

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.

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.

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.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ‘ ‘ is considered a whitespace character.
  • Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int myAtoi(string s) {
long answer = 0, len;
bool flag = true;
for(len = 0; len < s.length() && s[len] == ' '; len++){}
if(s[len] == '-') {
flag = false;
len++;
} else if(s[len] == '+')
len++;
else if('0' > s[len] || s[len] > '9')
return 0;

for(; len < s.length() && '0' <= s[len] && s[len] <= '9' && INT_MIN <= answer && answer <= INT_MAX; len++) {
answer = flag ? (answer<<3) + (answer<<1) + (s[len] & 0b1111) : answer * 10 - (s[len] & 0b1111);
}

return answer < INT_MIN ? INT_MIN : answer > INT_MAX ? INT_MAX : answer;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/10/PS/LeetCode/String-To-Integer-Atoi/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.