Leetcode 869: Reordered Power of 2

grid47
grid47
Exploring patterns and algorithms
Aug 12, 2024 5 min read

Given an integer n, check if it is possible to reorder its digits (in any order, including the original order) to form a number that is a power of two. Leading digits cannot be zero in the reordered number.
Problem
Approach
Steps
Complexity
Input: A single positive integer `n`.
Example: Input: n = 32
Constraints:
• 1 <= n <= 10^9
Output: Return `true` if it is possible to reorder the digits of `n` to form a power of two, otherwise return `false`.
Example: Output: true
Constraints:
• The output is a boolean value.
Goal: Determine if a permutation of the digits of `n` can result in a power of two.
Steps:
• Count the frequency of each digit in `n`.
• Iterate through all powers of two up to the maximum possible value within the constraints.
• Check if the frequency of digits in any power of two matches the frequency of digits in `n`.
• If a match is found, return `true`; otherwise, return `false`.
Goal: The solution must handle the given range of inputs efficiently.
Steps:
• 1 <= n <= 10^9
• Reordering must not allow leading zeros.
Assumptions:
• The input `n` is always a valid positive integer within the specified range.
• The number can be represented in base 10 without truncation.
Input: Input: n = 46
Explanation: The number 46 can be reordered to form 64, which is 2^6. Therefore, the output is `true`.

Input: Input: n = 123
Explanation: The number 123 cannot be reordered to form any power of two. Therefore, the output is `false`.

Input: Input: n = 8
Explanation: The number 8 is already a power of two (2^3). Therefore, the output is `true`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus