How do you think code with bitwise operators?
Background: Not a CS graduate.
Scenario: Reading this book, found a code snippet that looks like this:
# A power function in python using & and >> bitwise operators
def numpower(x, n):
res = 1
while n > 0:
if n & 1:
res = res * x
x = x * x
n = n >> 1
return res
Question: If someone had asked me to implement a power function, I'd have used recursion with dirty checking something like this.
Even though I followed the above python example with even and odd powers (n
) of any number (x
), I still couldn't understand how would one actually come up with this logic for this particular problem in the first place.
What I Tried: I could feel by tracking down the even odd case that the bitwise &
operator is doing a gateway check of some sorts that essentially behaves differently in the sequence of the while loop depending whether the power n
is even or odd, and the >>
shift operator is used to reduce n to sort of half (closest even number to the half of previous n
), but I couldn't put it all together.