String to Integer (atoi)

 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
class Solution:
    def myAtoi(self, input: str) -> int:
        sign = 1 
        result = 0
        index = 0
        n = len(input)

        INT_MAX = pow(2,31) - 1 
        INT_MIN = -pow(2,31)

        # Discard all spaces from the beginning of the input string.
        while index < n and input[index] == ' ':
            index += 1

        # sign = +1, if it's positive number, otherwise sign = -1. 
        if index < n and input[index] == '+':
            sign = 1
            index += 1
        elif index < n and input[index] == '-':
            sign = -1
            index += 1

        # Traverse next digits of input and stop if it is not a digit. 
        # End of string is also non-digit character.
        while index < n and input[index].isdigit():
            digit = int(input[index])

            # Check overflow and underflow conditions. 
            if ((result > INT_MAX // 10) or (result == INT_MAX // 10 and digit > INT_MAX % 10)):
                # If integer overflowed return 2^31-1, otherwise if underflowed return -2^31.    
                return INT_MAX if sign == 1 else INT_MIN

            # Append current digit to the result.
            result = 10 * result + digit
            index += 1

        # We have formed a valid number without any overflow/underflow.
        # Return it after multiplying it with its sign.
        return sign * result

Too many down votes. Junk problem.

 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
class Solution:
    def myAtoi(self, str: str) -> int:
        value, state, pos, sign = 0, 0, 0, 1

        if len(str) == 0:
            return 0

        while pos < len(str):
            current_char = str[pos]
            if state == 0:
                if current_char == " ":
                    state = 0
                elif current_char == "+" or current_char == "-":
                    state = 1
                    sign = 1 if current_char == "+" else -1
                elif current_char.isdigit():
                    state = 2
                    value = value * 10 + int(current_char)
                else:
                    return 0
            elif state == 1:
                if current_char.isdigit():
                    state = 2
                    value = value * 10 + int(current_char)
                else:
                    return 0
            elif state == 2:
                if current_char.isdigit():
                    state = 2
                    value = value * 10 + int(current_char)
                else:
                    break
            else:
                return 0
            pos += 1

        value = sign * value
        value = min(value, 2 ** 31 - 1)
        value = max(-(2 ** 31), value)

        return value

Language Agnostic Coding Drills

The code implements a string to integer conversion function, similar to the atoi function in C/C++. Here’s a breakdown of it into smaller units of learning:

Drill 1: Understanding the Problem Statement The first step to solving any problem is understanding the problem. This function takes a string and converts it to an integer. The function also handles spaces, positive/negative sign and ignores all the non-digit characters after considering the first non-space characters.

Drill 2: Basic String Handling Before we dive into the specific requirements of this function, it’s important to understand how to work with strings in general. The code uses basic string manipulation techniques, such as reading a character from a string.

Drill 3: Conditional Statements This code uses if-else statements to dictate the flow of the program. You need to understand how to use conditional statements to control which pieces of code get executed.

Drill 4: Looping through a String The code uses a while loop to iterate through the string. It’s crucial to understand how loops work, and how to use them to iterate through a string.

Drill 5: Working with States This code uses a state variable to track what it’s currently doing (ignoring leading spaces, handling the sign, reading digits). You need to understand how to use a variable to keep track of state.

Drill 6: Handling Leading Spaces The first part of the conversion ignores leading spaces. Practice writing a loop that skips over the leading spaces in a string.

Drill 7: Handling the Sign The next part of the conversion handles an optional sign at the beginning of the string. Practice writing code that handles an optional sign.

Drill 8: Reading Digits The main part of the conversion reads digits from the string and uses them to build an integer. Practice writing a loop that reads digits from a string and converts them to an integer.

Drill 9: Ignoring Trailing Non-Digit Characters The conversion stops reading the string as soon as it encounters a non-digit character. Practice writing a loop that stops reading a string when it encounters a non-digit character.

Drill 10: Handling Overflow The final part of the conversion checks for overflow and ensures the resulting integer is within the allowed range. Practice writing code that handles integer overflow.

Each of these drills covers a piece of the functionality of the myAtoi function. By practicing each drill separately, you can gain a better understanding of how the function works as a whole.

Targeted Drills in Python

Drill 1: Understanding the Problem Statement No coding needed, just understand the problem and what’s expected from the function.

Drill 2: Basic String Handling Get familiar with string operations in Python:

1
2
3
4
5
6
7
8
9
# Define a string
s = "Hello, World!"

# Get the length of the string
print(len(s))

# Access specific characters in the string
print(s[0])  # Output: "H"
print(s[-1]) # Output: "!"

Drill 3: Conditional Statements Understand how if-else statements work in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Define a variable
x = 10

# Use if-else statements to compare it with a value
if x > 10:
    print("x is greater than 10.")
elif x < 10:
    print("x is less than 10.")
else:
    print("x is equal to 10.")

Drill 4: Looping through a String Practice how to iterate through each character in a string using a for loop:

1
2
3
4
5
6
# Define a string
s = "Hello, World!"

# Loop through each character
for char in s:
    print(char)

Drill 5: Working with States Understand how to use a state variable in Python. No specific coding is required here, just understand that a variable can be used to keep track of states or stages in your logic.

Drill 6: Handling Leading Spaces Write a loop that skips over leading spaces in a string:

1
2
3
4
5
6
7
8
9
# Define a string
s = "    Hello, World!"

# Skip leading spaces
i = 0
while i < len(s) and s[i] == " ":
    i += 1
s = s[i:]
print(s)  # Output: "Hello, World!"

Drill 7: Handling the Sign Handle an optional sign at the beginning of the string:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Define a string
s = "-123"

# Check and handle the sign
if s[0] in ["+", "-"]:
    sign = s[0]
    s = s[1:]
else:
    sign = "+"
print(sign, s)  # Output: "-" "123"

Drill 8: Reading Digits Read digits from a string and convert them to an integer:

1
2
3
4
5
6
7
8
9
# Define a string
s = "123"

# Convert string to integer
num = 0
for char in s:
    if char.isdigit():
        num = num * 10 + int(char)
print(num)  # Output: 123

Drill 9: Ignoring Trailing Non-Digit Characters Stop reading a string when encountering a non-digit character:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Define a string
s = "123abc"

# Stop reading at non-digit character
num_str = ""
for char in s:
    if char.isdigit():
        num_str += char
    else:
        break
num = int(num_str)
print(num)  # Output: 123

Drill 10: Handling Overflow Handle integer overflow by limiting the maximum value:

1
2
3
4
5
6
7
8
9
# Define a large number
num = 2**33

# Check for overflow
if num > 2**31 - 1:
    num = 2**31 - 1
elif num < -2**31:
    num = -2**31
print(num)  # Output: 2147483647

In the drills, you are implementing the different parts of the function. After mastering these drills, you should be able to combine them into a complete solution.