Skip to content

Instantly share code, notes, and snippets.

@mattmess1221
Created March 3, 2022 20:21
Show Gist options
  • Save mattmess1221/d5c5d619da195d5829eebe6073a90538 to your computer and use it in GitHub Desktop.
Save mattmess1221/d5c5d619da195d5829eebe6073a90538 to your computer and use it in GitHub Desktop.
Python implementation of parseInt, which converts a value to a string, then reads until the first non-number.
ZERO = ord("0")
NINE = ord("9")
def parseInt(s):
result = None
for i in str(s):
ascii_value = ord(i)
if ZERO <= ascii_value <= NINE:
result = result or 0
result *= 10
result += ascii_value - ZERO
else:
break
return result
print(parseInt(0.5)) # 0
print(parseInt(0.05)) # 0
print(parseInt(0.005)) # 0
print(parseInt(0.0005)) # 0
print(parseInt(0.00005)) # 5, note: python starts using scientific notation here
print(parseInt(0.000005)) # 5
print(parseInt(0.0000005)) # 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment