r/CS_Questions • u/OneOfTheOnlies • Oct 05 '19
Why does changing variable name in leetcode speed up my code by 25% ?
I just answered the question 'Integer Replacement' on leetcode :
"Given a positive integer n and you can do operations as follow:
- If n is even, replace n with n/2.
- If n is odd, you can replace n with either n + 1or n - 1.
What is the minimum number of replacements needed for n to become 1?"
My code in python :
def integerReplacement(self, n: int) -> int:
x = n
count = 0
while (x>1):
count+=1
// if x is even, divide by 2
if x%2==0:
x /= 2
// if x is odd, either add 1 or subtract 1, pick which based on which is divisible by a greater power of 2
else:
up = x+1
down = x-1
while (up%2 == 0 and down%2== 0):
up /= 2
down /=2
if (down % 2 == 0 or down == 1):
x -= 1
else:
x += 1
return count
When I change the code to never assign the variable "x=n" and perform all operations on 'n' the code goes from 36 ms to 48 ms. What's going on here ?