Solving Leetcode Interviews in Seconds with AI: Power of Two
Introduction
In this blog post, we will explore how to solve the LeetCode problem "231" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion?
Explanation
Here's the breakdown of the solution and the Python code:
Approach:
- Handle non-positive numbers: Powers of two are always positive, so immediately return
Falseifnis zero or negative. - Bitwise AND: A power of two has only one bit set to 1 in its binary representation. The expression
n & (n - 1)will be zero if and only ifnis a power of two. This works because subtracting 1 from a power of two flips all the bits from the rightmost set bit to the end.
- Handle non-positive numbers: Powers of two are always positive, so immediately return
Complexity:
- Runtime: O(1)
- Storage: O(1)
Code
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
return (n & (n - 1)) == 0