LeetCode 0869. Reordered Power of 2 Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0869. Reordered Power of 2

Description

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

Solution 1: Enumeration

We can enumerate all powers of 2 in the range [1, 109] and check if their digit composition is the same as the given number.

Define a function f(x) that represents the digit composition of number x. We can convert the number x into an array of length 10, or a string sorted by digit size.

First, we calculate the digit composition of the given number n as target = f(n). Then, we enumerate i starting from 1, shifting i left by one bit each time (equivalent to multiplying by 2), until i exceeds 109. For each i, we calculate its digit composition and compare it with target. If they are the same, we return true; if the enumeration ends without finding the same digit composition, we return false.

Time complexity O(log^2 M), space complexity O(log M). Where M is the upper limit of the input range {10}9 for this problem.

PythonJavaC++GoTypeScriptRust
class Solution: def reorderedPowerOf2(self, n: int) -> bool: def f(x: int) -> List[int]: cnt = [0] * 10 while x: x, v = divmod(x, 10) cnt[v] += 1 return cnt target = f(n) i = 1 while i <= 10**9: if f(i) == target: return True i <<= 1 return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !