Skip to content

Instantly share code, notes, and snippets.

@bcambel
Created February 9, 2016 17:25
Show Gist options
  • Select an option

  • Save bcambel/96099bd6d2ed0c71e08a to your computer and use it in GitHub Desktop.

Select an option

Save bcambel/96099bd6d2ed0c71e08a to your computer and use it in GitHub Desktop.
Custom String to Integer
import math
def atoi(s):
return "".join(map(lambda x: str(ord(x)), s))
print [ord(str(i)) for i in range(1,10)]
print ord("+")
def myAtoi(s):
"""
:type str: str
:rtype: int
"""
if len(s) == 0:
return 0
possibles = []
sign = False
spaceEnd = False
for i in s:
ordinal = ord(i)
#print i, ordinal
if 57 >= ordinal >= 48:
spaceEnd = True
possibles.append(i)
elif ordinal in [32] :
if spaceEnd:
break
pass
elif ordinal == 43:
spaceEnd=True
if sign:
return 0
else:
sign = True
elif ordinal == 45:
spaceEnd=True
if sign:
return 0
sign = True
possibles.append(i)
else:
break
#elif ordinal ==
try:
res = int("".join(possibles))
if res > 2147483647:
return 2147483647
elif res < -2147483648:
return -2147483648
else:
return res
except ValueError:
return 0
print myAtoi(" -0012ab56")
print myAtoi("123 456")
print myAtoi(" -123")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment