|
| 1 | +# Power of Two |
| 2 | + |
| 3 | +Given an integer n, return true if it is a power of two. Otherwise, return false. |
| 4 | + |
| 5 | +An integer n is a power of two, if there exists an integer x such that n == 2x. |
| 6 | + |
| 7 | +## Examples |
| 8 | + |
| 9 | +Example 1: |
| 10 | +```text |
| 11 | +Input: n = 1 |
| 12 | +Output: true |
| 13 | +Explanation: 2^0 = 1 |
| 14 | +``` |
| 15 | + |
| 16 | +Example 2: |
| 17 | +```text |
| 18 | +Input: n = 16 |
| 19 | +Output: true |
| 20 | +Explanation: 2^4 = 16 |
| 21 | +``` |
| 22 | + |
| 23 | +Example 3: |
| 24 | + |
| 25 | +```text |
| 26 | +Input: n = 3 |
| 27 | +Output: false |
| 28 | +``` |
| 29 | + |
| 30 | +## Constraints |
| 31 | + |
| 32 | +- -2^31 <= n <= 2^31 - 1 |
| 33 | + |
| 34 | + |
| 35 | +> Follow up: Could you solve it without loops/recursion? |
| 36 | +
|
| 37 | +## Solution |
| 38 | + |
| 39 | +The main idea of this solution is to use bit manipulation to check whether a number contains only one set bit in its |
| 40 | +binary representation. Powers of two are always positive and have exactly one bit set to 1, while all other bits are 0. |
| 41 | +First, verify that the number is greater than zero, as negative numbers and zero cannot be powers of two. Then, use the |
| 42 | +property that for any power of two, subtracting 1 from n turns the rightmost 1-bit into 0 and flips all bits to the right |
| 43 | +of it to 1. Performing a bitwise AND between n and n - 1 gives zero only for powers of two, confirming that the number |
| 44 | +contains exactly one set bit. |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +Using the intuition above, we implement the algorithm as follows: |
| 49 | + |
| 50 | +- If n is less than or equal to zero, return FALSE. |
| 51 | +- Compute n - 1 to flip all bits after the rightmost 1-bit in the binary representation of n. |
| 52 | +- Perform a bitwise AND between n and n - 1. |
| 53 | +- Return TRUE if the result of the above computation is 0; FALSE otherwise. |
| 54 | + |
| 55 | +Let’s look at the following illustration to get a better understanding of the solution: |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | +### Time Complexity |
| 65 | + |
| 66 | +The algorithm’s time complexity is O(1) because it performs only a fixed number of arithmetic and bitwise operations, |
| 67 | +regardless of the value of n. |
| 68 | + |
| 69 | +### Space Complexity |
| 70 | + |
| 71 | +The algorithm’s space complexity is constant, O(1). |
0 commit comments