Skip to content

900. Reordered Power Of 2

Hash Table Math Sorting Counting Enumeration

Problem - Reordered Power Of 2

Medium

You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.

Return true if and only if we can do this so that the resulting number is a power of two.

 

Example 1:

Input: n = 1
Output: true

Example 2:

Input: n = 10
Output: false

 

Constraints:

  • 1 <= n <= 109

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def reorderedPowerOf2(self, n: int) -> bool:

        def counter(val: int) -> List[int]:
            count = [0] * 10 # Max digits
            while val:
                val, remain = divmod(val, 10)
                count[remain] += 1
            return count

        target = counter(n)
        i = 1
        while i < 10**9:
            if counter(i) == target:
                return True
            i <<= 1 # Bitwise shift left
        return False

Submission Stats:

  • Runtime: 0 ms (100.00%)
  • Memory: 17.6 MB (86.39%)