leet链接:https://leetcode.com/problems/string-to-integer-atoi/description/
问题描述:
Implement atoi
which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
我的python实现:
def atoi(s):
sign = "+"
before = True
res = 0
for v in s:
if v == " " and before:
continue
elif (v == "+" or v == "-") and before:
sign = v
elif (ord(v) < 48 or ord(v) > 57) and before:
return 0
elif not before and not 48 <= ord(v) <= 57:
return -1 * res if sign == "-" else res
elif 48 <= ord(v) <= 57:
before = False
res = res * 10 + (ord(v) - 48)
else:
pass
return -1 * res if sign == "-" else res
if __name__ == "__main__":
s = input("input string:")
print("The converted result is ", atoi(s))