This is the first in a series of posts dissecting typical coding interview questions. I will begin with a pretty simple one - reversing an integer.
def reverse_int(n):
rev = 0
while num > 0: # n < 10 / 10 = 0
rev = rev * 10 # shift current rev to left to append digit
rev = rev + (num % 10) # get last digit of num
num = num / 10 # chop off last digit of num
Tracing a Call
reverse_int(492)
- Loop 1
rev
is0
rev
isrev * 10 = 0
rev
isrev
+ (num % 10) = 2num
= 49
- Loop 2
rev
isrev
* 10 = 20rev
isrev
+ (num % 10) = 29num
= 4
- Loop 3
rev
=rev * 10
= 290rev
=rev
+ (num % 10) = 294num
= 0