...

/

Solution Review: String to Integer

Solution Review: String to Integer

This lesson contains the solution review to convert a string into an integer in Python.

We'll cover the following...

In this lesson, we will review the solution to the challenge in the last lesson. The problem is as follows:

Given some numeric string as input, convert the string to an integer.

You already know that we are not allowed to use the built-in int() function. Now to convert a string into an integer, we can make use of the following arithmetic:

As you can see, by multiplying each digit with the appropriate base power, we can get the original integer back. Let’s implement this in Python.

Implementation

Press + to interact
def str_to_int(input_str):
output_int = 0
if input_str[0] == '-':
start_idx = 1
is_negative = True
else:
start_idx = 0
is_negative = False
for i in range(start_idx, len(input_str)):
place = 10**(len(input_str) - (i+1))
digit = ord(input_str[i]) - ord('0')
output_int += place * digit
if is_negative:
return -1 * output_int
else:
return output_int
s = "554"
x = str_to_int(s)
print(type(x))
s = "123"
print(str_to_int(s))
s = "-123"
print(str_to_int(s))

Explanation

On line 3, output_int is initialized to 0. The code on lines 5-10 ...