Convert string to integer without using built-in functions

preview_player
Показать описание
Python code:
def Convert_string_to_integer(num_str):
res = 0
for i in num_str:
res = res * 10 + (ord(i) - 48)
return res

num_str = input()
print(num_str)
print(type(num_str))
result = Convert_string_to_integer(num_str)
print(result)
print(type(result))

Explanation:
Iteration 1: res = 0 * 10 + (ord('1') - 48) -- (49 - 48) = 1
Iteration 2: res = 1 * 10 + (ord('2') - 48) -- (50 - 48) = 12
Iteration 3: res = 12 * 10 + (ord('3') - 48) -- (51 - 48) = 123
Iteration 4: res = 123 * 10 + (ord('4') - 48) -- (52 - 48) = 1234
Iteration 5: res = 1234 * 10 + (ord('5') - 48) -- (53 - 48) = 12345
The final result is 12345.
Рекомендации по теме