LeetCode 869: Reordered Power of 2 Solution

Master LeetCode problem 869 (Reordered Power of 2), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

869. Reordered Power of 2

Problem Explanation

Explanation

To solve this problem, we can generate all possible permutations of the digits of the input number n, check if any of these permutations form a power of 2, and return true if we find one. We can use a helper function to check if a number is a power of 2 efficiently.

Algorithm:

  1. Convert the integer n to a string to easily manipulate its digits.
  2. Generate all permutations of the digits of n.
  3. For each permutation:
    • Convert the permutation back to an integer.
    • Check if the integer is a power of 2 using the helper function.
  4. If any permutation is a power of 2, return true. Otherwise, return false.

Time Complexity: O((log n)! * log n) where log n is the number of digits in n. Space Complexity: O(log n) for storing the permutations and recursive calls.

Solution Code

class Solution {
    public boolean reorderedPowerOf2(int n) {
        String num = Integer.toString(n);
        return permutationHelper(num.toCharArray(), 0);
    }
    
    private boolean permutationHelper(char[] arr, int index) {
        if (index == arr.length) {
            String numStr = new String(arr);
            if (numStr.charAt(0) != '0' && isPowerOfTwo(Integer.parseInt(numStr))) {
                return true;
            }
        }
        
        for (int i = index; i < arr.length; i++) {
            if (index == 0 && arr[i] == '0') continue;
            swap(arr, index, i);
            if (permutationHelper(arr, index + 1)) {
                return true;
            }
            swap(arr, index, i);
        }
        return false;
    }
    
    private void swap(char[] arr, int i, int j) {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    private boolean isPowerOfTwo(int num) {
        return num > 0 && (num & (num - 1)) == 0;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 869 (Reordered Power of 2)?

This page provides optimized solutions for LeetCode problem 869 (Reordered Power of 2) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 869 (Reordered Power of 2)?

The time complexity for LeetCode 869 (Reordered Power of 2) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 869 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 869 in Java, C++, or Python.

Back to LeetCode Solutions