Python string to integer

Normally when you want to convert a string to an integer you would just use Python’s built-in function int(). This function takes the string you want to convert as a parameter and returns the integer value of that string.

For example,

				
					x = "123"
print(f"{x} is of type: {type(x)}")

x = int(x)
print(f"{x} is of type: {type(x)}")
				
			

OUTPUT

				
					123 is of type: <class 'str'>
123 is of type: <class 'int'>
				
			

and this works perfectly fine. But, sometimes you need to convert a string to integer without using Python’s built-in int() function.

BUT WHY?

This came about when working on the LeetCode challenge multiply strings. They want you to multiply two non-negative integers that are represented as strings, but you can not use any built-in BigInteger library or convert the inputs to integer directly.

HOW SWAY?

This may not be the best solution for solving this challenge, but there are many ways to skin a cat and this post is more focused on a way to convert a string to integer without using int(). And it works! That being said, this approach did beat 99.20% of all challenge entries in regards to runtime with a time of 23ms. In the memory ranking, it beat 96.72% with a size of 13.7MB.

In a nutshell, this is can be done using Python’s built-in function ord().

The ord() function returns an integer representing the Unicode character.

For example,

				
					print(ord("0"))
print(ord("1"))
print(ord("2"))
print(ord("3"))
print(ord("4"))
print(ord("5"))
print(ord("6"))
print(ord("7"))
print(ord("8"))
print(ord("9"))
				
			

OUTPUT

				
					48
49
50
51
52
53
54
55
56
57
				
			

As you can see ord('0') equals 48. Using this value as the subtrahend we can apply basic math to infer a integer value for a number character.

				
					print(ord("1") - ord("0"))
print(ord("2") - ord("0"))
print(ord("3") - ord("0"))
				
			

OUTPUT

				
					1
2
3
				
			

Putting it all together we can create a simple function to loop through each character in the string and construct a complete whole number from the string value.

				
					def convert_str_to_int(str_num):
    sum = 0
    for i in str_num:
        minuend = ord(i)
        subtrahend = ord('0')
        if not(minuend >= 48 and minuend <= 57):
            print(f"this string {str_num} is not a number")
            return None      
        diff = minuend - subtrahend
        sum = sum*10 + diff
    return sum

x = "123"
print(f"{x} is of type: {type(x)}")

x = convert_str_to_int(x)
print(f"{x} is of type: {type(x)}")
				
			

OUTPUT

				
					123 is of type: <class 'str'>
123 is of type: <class 'int'>
				
			
bdot
bdotmilby@gmail.com
No Comments

Post A Comment