↓Skip to main content
  1. LeetCode/

LeetCode 342: Power of Four

·1 min· ·
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-23

  • Submissions: Accepted (first try)

Approach
#

A power of four is a power of two whose single 1 sits at bit 0, 2, 4, … (Bit Manipulation). 0x55555555 is 0101...01 in binary, exactly the even positions, so test n & 0x55555555 != 0. Alternatively 4^k = (3 + 1)^k ≡ 1 (mod 3) while 2 × 4^k ≡ 2 (mod 3).

My Attempts
#

Passed on the first try with n > 0 and n & (n - 1) == 0 and n % 3 == 1, the mod-3 test.

Solution
#

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

Complexity
#

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

Mistakes to Avoid
#

  • Checking a power of two is not enough: 2 and 8 are not powers of four.

Interview Explanation
#

A power of four is a power of two with its 1 at an even position, so I check for a single bit with n & (n - 1) and its position by AND-ing with 0x55555555. Time O(1).

Related

LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
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 326: Power of Three
·1 min
LeetCode Easy Math Recursion
LeetCode 326 note: divide by 3 while possible and check for 1; without loops, n is a power of three exactly when it divides 3^19
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt