In the above diagram:
DIGIT | → | the characters "0" thru "9" |
SIGN | → | the character "+" or "-" |
Note: The starting and ending spaces have been removed from the string.
Python Code - Parse an Integer
# ==========================================================
# String to Integer Conversion
# ----------------------------------------------------------
# This is not the most efficient code. I designed it as
# a demonstration for easier reading/understanding.
# ==========================================================
# ----------------------------------------------------------
# convert string to an integer
# ----------------------------------------------------------
def string_to_integer(str):
# --- initialize local variables
i = 0 # string character index
l = len(str) # string length
vp = True # value is positive
v = 0 # string's integer value
# --- test string length
if l == 0:
return False,0
# --- process string
sign = False # found a [+-] character
while i < l:
c = str[i] # get a string character
print('c={},v={},i={}'.format(c,v,i))
i = i + 1 # increment string index
if c == "+": # character "+"
if sign: # found more that one sign?
return False,0 # error
sign = True # found + sign
elif c == "-": # character "-"
if sign: # found more that one sign?
return False,0 # error
sign = True # found - sign
vp = False # value is negative
elif c == "0": # character "0"
v = v*10
elif c == "1": # character "1"
v = (v*10) + 1
elif c == "2": # character "2"
v = (v*10) + 2
elif c == "3": # character "3"
v = (v*10) + 3
elif c == "4": # character "4"
v = (v*10) + 4
elif c == "5": # character "5"
v = (v*10) + 5
elif c == "6": # character "6"
v = (v*10) + 6
elif c == "7": # character "7"
v = (v*10) + 7
elif c == "8": # character "8"
v = (v*10) + 8
elif c == "9": # character "9"
v = (v*10) + 9
else: # illegal character
return False,0
if not vp: # negative value?
v = -v
return True,v # end of string