Lets say you have a string "leet23code" and you want to parse the characters as number 23, and you are not allowed to typecast after collecting the complete number "23" as string.
Its not really a trick but its just a nice way to build the number from string.
The obvious way to do this is by multiplying the position of digit in number and adding it, for example 23 can be represented as
(2 * 10 ^ 1 ) + (3 * 10 ^ 0)
we would need to keep track of the power of 10 to build the number
something like
power = 0
my_number = 0
for c in s:
if c.isnumeric():
my_number += int(c) + 10 * power
power += 1
This is nice and easy to understand, but there is even a better trick than this
def parse_number(self, s):
my_number = 0
for c in s:
if c.isnumeric():
my_number = my_number * 10 + int(c)
return my_number
This reduces the need for keeping track of power, because we knew power is incremented every time.
0 comments:
Post a Comment