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 <= 109One approach to solve the problem is to leverage the fact that two numbers with the same digits in different orders will have the same digit frequency (or count of each digit). For the given number n, we aim to check if its digits can be rearranged to form any power of two. To achieve this:
10^9 and store their digit frequency in a set.n, calculate its digit frequency and check if it exists in the set.The implementation uses an array to count the frequency of each digit in n. It then iterates through all powers of two that can exist within the limits (2^0 to 2^30). For each power, it calculates the digit frequency and compares it to n's. If a match is found, it returns true. If no match is found through all powers, it returns false.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1) because the number of power of twos checked (31) and the frequency array size (10) are constant.
Space Complexity: O(1) as only small fixed-size integer arrays are used.
A backtracking method can be employed by generating permutations of the digits of the number n and checking if any results in a power of two. Given the constraint, this method needs optimization to efficiently discard invalid permutations early.
n's digits where the leading digit isn't zero.Permutations in C would require explicit handling of stateful recursion and result collections, a task not directly suited for this predefined response format.
C++
Java
Python
C#
JavaScript
Not provided due to complexity constraints in inline format.
| Approach | Complexity |
|---|---|
| Digit Count Matching with Powers of Two | Time Complexity: O(1) because the number of power of twos checked (31) and the frequency array size (10) are constant. |
| Backtracking Approach | Not provided due to complexity constraints in inline format. |
Reordered Power of 2 | Live Coding with Explanation | Leetcode - 869 • Algorithms Made Easy • 6,070 views views
Watch 9 more video solutions →Practice Reordered Power of 2 with our built-in code editor and test cases.
Practice on FleetCode