LeetCode 231: Power of Two

Problem Description

Explanation

To determine if an integer is a power of two, we can check if there is only one bit set in its binary representation. If there is exactly one bit set, then the number is a power of two. We can achieve this by performing a bitwise AND operation between the number and its predecessor i.e., n & (n-1). If the result is 0, then the number is a power of two.

  • Time complexity: O(1)
  • Space complexity: O(1)

Solutions

class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        return (n & (n - 1)) == 0;
    }
}

Loading editor...