This code checks if the input `n` (a `long` integer)...

August 30, 2025 at 06:29 AM

bool isPowerOfTwo(long n) { return (n > 0) && ((n & (n - 1)) == 0); }

This code checks if the input n (a long integer) is a power of two. Here's how it works:

Step-by-step explanation:

  1. n > 0:

    • This checks if n is a positive number. Only positive numbers can be powers of two, so this is a necessary condition.
  2. Bitwise operation: (n & (n - 1)) == 0:

    • This checks the bit representation of the number n.
    • A power of two has exactly one bit set to 1 in its binary representation. For example:
      • 1 is 0001 in binary.
      • 2 is 0010 in binary.
      • 4 is 0100 in binary.
      • 8 is 1000 in binary.
    • Subtracting 1 from a power of two flips all the bits after (and including) the rightmost 1:
      • For 4 (0100), 4 - 1 = 3 (0011).
      • For 8 (1000), 8 - 1 = 7 (0111).
    • If you perform a bitwise AND operation (&) between a power of two (n) and n - 1, the result will always be 0:
      • 4 & 3 = 0100 & 0011 = 0000
      • 8 & 7 = 1000 & 0111 = 0000
    • If n is not a power of two, the result will not be 0.
  3. Return value:

    • The function returns true if both conditions are met (i.e., n is positive and (n & (n - 1)) == 0), meaning n is a power of two.
    • Otherwise, it returns false.

Summary:

The function determines if n is a power of two by ensuring n > 0 and verifying its unique property in binary: having exactly one bit set to 1.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node