I can’t resist simple bithacks for calculating interesting properties of numbers. One of the classic ones, which is trivial once you know the “trick” but can be maddening if not, is whether a given number is a power of two. I don’t have any great hints on how to solve this problem, but I can say that imagining a binary counter increasing, and noticing what was happening differently when it reached a power of two, helped me. And if that doesn’t help, well, do you see what I mean about it being maddening?

If you’ve figured it out, or don’t mind spoilers, here’s my (very simple) code with explanatory comment.

def isPowTwo(n):
  if n == 0:
    return False
  # The only numbers where the most significant bit
  # does not equal that of its successor is with 2^n - 1 and 2^n
  # In that case, all of the bits differ
  return not ((n-1) & n)

def test(n):
  print("isPowTwo({}) == {}".format(n, isPowTwo(n)))

for i in [0,1,2,3,4,5,6,7,8,9,10,11,248023]: