# Question

Formatted question description: https://leetcode.ca/all/8.html

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
6. Return the integer as the final result.

Note:

• Only the space character ' ' is considered a whitespace character.
• Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Example 1:

Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.


Example 2:

Input: s = "   -42"
Output: -42
Explanation:
^
Step 2: "   -42" ('-' is read, so the result should be negative)
^
Step 3: "   -42" ("42" is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.


Example 3:

Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.


Constraints:

• 0 <= s.length <= 200
• s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.

# Algorithm

This question only needs to consider the numbers and symbols:

1. If the string starts with a space, all spaces are skipped to the first non-space character, if there is no space, 0 is returned.

2. If the first non-space character is the sign +/-, then the sign is true or false. This question has a limitation, that is, in C++, both +-1 and -+1 are accepted, both It is -1, but in this question, it will return 0.

3. If the next character is not a number, it returns 0, regardless of the decimal point and natural numbers, but this is fine, at least it saves a lot of trouble.

4. If the next character is a number, it will be converted to plastic and saved. If a non-number appears next, the current result will be returned.

5. Also need to consider the boundary problem, if it exceeds the range of the integer number, use the boundary value to replace the current value.

# Code

• 
public class String_to_Integer {

// I just added "index < str.length()" to every step, to pass test case : " "
class Solution {
public int myAtoi(String str) {

int index = 0, sign = 1, total = 0;

//1. Empty string
if(str.length() == 0) {
return 0;
}

//2. Remove Spaces
while(index < str.length() && str.charAt(index) == ' ') {
index++;
}

//3. Handle signs
if(index < str.length() && (str.charAt(index) == '+' || str.charAt(index) == '-')){
sign = str.charAt(index) == '+' ? 1 : -1;
index ++;
}

//4. Convert number and avoid overflow
while(index < str.length()){
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9) {
break;
}

//check if total will be overflow after 10 times and add digit
if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}

total = 10 * total + digit;
index ++;
}
}

}
}


• // OJ: https://leetcode.com/problems/string-to-integer-atoi/
// Time: O(N)
// Space: O(1)
class Solution {
public:
int myAtoi(string s) {
int i = 0, N = s.size(), sign = 1, ans = 0;
while (i < N && s[i] == ' ') ++i;
if (i < N && (s[i] == '+' || s[i] == '-')) sign = s[i++] == '+' ? 1 : -1;
while (i < N && isdigit(s[i])) {
int n = s[i++] - '0';
if (ans > INT_MAX / 10 || (ans == INT_MAX / 10 && n > INT_MAX % 10)) return sign == 1 ? INT_MAX : INT_MIN;
ans = ans * 10 + n;
}
return ans * sign;
}
};

• class Solution:
def myAtoi(self, s: str) -> int:
if not s:
return 0
n = len(s)
if n == 0:
return 0
i = 0
while s[i] == ' ':
i += 1
# only contains blank space
if i == n:
return 0
sign = -1 if s[i] == '-' else 1
if s[i] in ['-', '+']:
i += 1
res, flag = 0, (2**31 - 1) // 10
while i < n:
# not a number, exit the loop
if not s[i].isdigit():
break
c = int(s[i])
# if overflows
if res > flag or (res == flag and c > 7):
return 2**31 - 1 if sign > 0 else -(2**31)
res = res * 10 + c
i += 1
return sign * res

############

class Solution(object):
def myAtoi(self, s):
"""
:type str: str
:rtype: int
"""
s = s.strip()
sign = 1
if not s:
return 0
if s in ["+", "-"]:
if s == "-":
sign = -1
s = s[1:]
ans = 0
for c in s:
if c.isdigit():
ans = ans * 10 + int(c)
else:
break
ans *= sign
if ans > 2147483647:
return 2147483647
if ans < -2147483648:
return -2147483648
return ans


• func myAtoi(s string) int {
i, n := 0, len(s)
num := 0

for i < n && s[i] == ' ' {
i++
}
if i == n {
return 0
}

sign := 1
if s[i] == '-' {
sign = -1
i++
} else if s[i] == '+' {
i++
}

for i < n && s[i] >= '0' && s[i] <= '9' {
num = num*10 + int(s[i]-'0')
i++
if num > math.MaxInt32 {
break
}
}

if num > math.MaxInt32 {
if sign == -1 {
return math.MinInt32
}
return math.MaxInt32
}
return sign * num
}


• const myAtoi = function (str) {
str = str.trim();
if (!str) return 0;
let isPositive = 1;
let i = 0,
ans = 0;
if (str[i] === '+') {
isPositive = 1;
i++;
} else if (str[i] === '-') {
isPositive = 0;
i++;
}
for (; i < str.length; i++) {
let t = str.charCodeAt(i) - 48;
if (t > 9 || t < 0) break;
if (ans > 2147483647 / 10 || ans > (2147483647 - t) / 10) {
return isPositive ? 2147483647 : -2147483648;
} else {
ans = ans * 10 + t;
}
}
return isPositive ? ans : -ans;
};


• ﻿// https://leetcode.com/problems/string-to-integer-atoi/

public partial class Solution
{
public int MyAtoi(string str)
{
int i = 0;
long result = 0;
bool minus = false;
while (i < str.Length && char.IsWhiteSpace(str[i]))
{
++i;
}
if (i < str.Length)
{
if (str[i] == '+')
{
++i;
}
else if (str[i] == '-')
{
minus = true;
++i;
}
}
while (i < str.Length && char.IsDigit(str[i]))
{
result = result * 10 + str[i] - '0';
if (result > int.MaxValue)
{
break;
}
++i;
}
if (minus) result = -result;
if (result > int.MaxValue)
{
result = int.MaxValue;
}
if (result < int.MinValue)
{
result = int.MinValue;
}
return (int)result;
}
}