Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Build confidence with an intuition-first walkthrough focused on math fundamentals.
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 - 1Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Bit Manipulation
1
16
3
number-of-1-bits)power-of-three)power-of-four)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #231: Power of Two
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
// Accepted solution for LeetCode #231: Power of Two
func isPowerOfTwo(n int) bool {
return n > 0 && (n&(n-1)) == 0
}
# Accepted solution for LeetCode #231: Power of Two
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
// Accepted solution for LeetCode #231: Power of Two
impl Solution {
pub fn is_power_of_two(n: i32) -> bool {
n > 0 && (n & (n - 1)) == 0
}
}
// Accepted solution for LeetCode #231: Power of Two
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.