Created
August 16, 2019 19:04
-
-
Save discrimy/2995ae7b3628bb0337d378a38f30745a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char_to_dig = { | |
'0': 0, | |
'1': 1, | |
'2': 2, | |
'3': 3, | |
'4': 4, | |
'5': 5, | |
'6': 6, | |
'7': 7, | |
'8': 8, | |
'9': 9, | |
} | |
def atoi(string: str): | |
# Убираем пробелы и другое в начале | |
string = string.lstrip() | |
# Ищем конец числа | |
num_end = None | |
for i in range(1 if string[0] == '-' else 0, len(string)): | |
if string[i] not in char_to_dig: | |
num_end = i | |
break | |
if i == len(string) - 1: | |
num_end = len(string) | |
if num_end is None: | |
return 0 | |
result = 0 | |
for i in range(num_end): | |
# i - порядковый номер числа, j - индекс символа | |
j = num_end - i - 1 | |
char = string[j] | |
# Если в конце знак минуса, то число нужно сделать отрицательным | |
if char == '-': | |
if j == 0: | |
result *= -1 | |
continue | |
else: | |
return -1 | |
# Соотношение символа к цифре, если не цифра, то вернуть 0 | |
digit = char_to_dig.get(char, None) | |
if digit is None: | |
return -1 | |
result += digit * 10**i | |
return result | |
print(atoi("0")) | |
print(atoi(" 10234")) | |
print(atoi(" \t-10234")) | |
print(atoi("\t\n -102f34")) | |
print(atoi("sometext")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment