↓Skip to main content
  1. LeetCode/

LeetCode 231: Power of Two

·2 mins· ·
LeetCode Easy Math Bit-Manipulation Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-22

  • Submissions: Wrong Answer ×3 → Accepted → Wrong Answer → Accepted

Approach
#

n & (n - 1) clears the lowest set bit (Bit Manipulation). A power of two has a single 1, so the result is 0. Zero and negatives are not powers of two and must be excluded.

My Attempts
#

  • Attempt 1 wrote (n > 0) & (n & (n - 1)) == 0; & binds tighter than ==, so n = 0 became (False & 0) == 0 and returned True.
  • The next dropped == 0, meaning “n & (n - 1) is nonzero”, the opposite: 4 returned 0. A 2022-11 rewrite repeated n > 0 and n & (n - 1); adding not passed.

Solution
#

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • Python’s & binds tighter than ==: (n > 0) & (n & (n - 1)) == 0 means ((n > 0) & (n & (n - 1))) == 0. Join the conditions with and.
  • It is a power of two when n & (n - 1) is 0, not the other way around.

Interview Explanation
#

A power of two has one set bit, and n & (n - 1) clears the lowest one, so I check that n is positive and n & (n - 1) is 0. Time O(1).

Related

LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 234: Palindrome Linked List
·2 mins
LeetCode Easy Linked-List Two-Pointers Stack Recursion
LeetCode 234 note: find the middle with fast and slow pointers, reverse the second half, and compare from both ends with O(1) extra space
LeetCode 258: Add Digits
·1 min
LeetCode Easy Math Simulation Number-Theory
LeetCode 258 note: sum the digits repeatedly until one remains; the O(1) answer is the digital root 1 + (n - 1) % 9
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)
LeetCode 202: Happy Number
·1 min
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 note: repeatedly take the sum of squared digits, which reaches 1 or enters a cycle; detect it with a set of seen numbers or fast and slow pointers
LeetCode 203: Remove Linked List Elements
·2 mins
LeetCode Easy Linked-List Recursion
LeetCode 203 note: the head may be deleted too, so a dummy head turns every deletion into deleting cur.next; do not advance after deleting