Skip to content

Instantly share code, notes, and snippets.

@kefeimo
Created July 8, 2021 15:15
Show Gist options
  • Save kefeimo/8d21b3da63dbe710a6c9ceeb7ce132c5 to your computer and use it in GitHub Desktop.
Save kefeimo/8d21b3da63dbe710a6c9ceeb7ce132c5 to your computer and use it in GitHub Desktop.
"""
Task: Write a method that takes a string as an input and converts it to an integer.
Do not use any type of built in methods like int.Parse or atoi.
Solution:
Strategy:
1. Use regular expression to check if the input is a valid numeric string
2. Use decimal number definition to construct the integer (e.g., 23 = 2*10+3, 134 = (1*10+3)*10+4), -3 = -(3))
"""
import re
def numstring_to_integer(numstring, allowed_leading_zeros=False):
"""
Convert a numeric string input to an integer without using built-in parse functions
The function only convert valid numeric strings. e.g.,
Valid numeric strings: "4094499383228822200494837", "-193", "0004532", "-009284" (when allowing leading zeros)
Invalid numeric strings: "d993", "00-343", "+4544", "--34"
:param numstring: str, numeric string input
:param allowed_leading_zeros: bool, if True allowing leading zeros
:return: int or None, if the input is valid numeric string. Otherwise return None
"""
# Check if the input string is a valid integer (use regular expression)
if not allowed_leading_zeros: # NOT allow leading 0s
is_integer = re.match("[-]?[1-9]+[0-9]*$", numstring)
else:
is_integer = re.match("[-]?[0-9]+$", numstring)
# Convert the string input to int if the input is a valid numeric string.
# If not a valid numeric string. Print out the error.
if not is_integer:
print(f"ERROR: The input {numstring} is NOT a valid integer!!!")
else:
dict_str_to_int = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
result_int = 0
for num_str in numstring:
if num_str != '-': # handle negative value
result_int = 10 * result_int + dict_str_to_int.get(num_str) # use decimal number definition
if numstring.startswith('-'):
result_int = -result_int
return result_int
if __name__ == "__main__":
string_input = input("""
Convert a numeric string to an integer.
TYPE a NUMBER and PRESS \"ENTER\" (Leave empty to test the default cases):
""")
print()
# Allow leading zeros
if string_input:
result = numstring_to_integer(string_input, allowed_leading_zeros=True)
print(f"The numeric string input is: {string_input}, type: {type(string_input)}")
print(f"Convert to integer: {result}, type: {type(result)}")
else:
default_test_cases = ["4094499383228822200494837",
"-193",
"d993",
"0004532",
"-009284",
"00-343",
"+4544",
"--34"]
for i, case in enumerate(default_test_cases):
result = numstring_to_integer(case, allowed_leading_zeros=True)
print(f"Test case {i}")
print(f"The numeric string input is: {case}")
print(f"Convert to integer: {result}")
print("-----------------------")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment