Leetcode 869. Reordered Power of 2
You are given an integer n. Reorder the digits of n (in any order) such that the resulting number is a power of two. Return true if possible, otherwise return false.
n be a non-negative integer for sure?
n will be a non-negative integer as per the problem’s context.n?
n is within the range of a 32-bit signed integer in problems like these (0 to 2,147,483,647).n have leading zeroes after reordering its digits?
n.n matches with any of the sorted sequences in the set of powers of 2.import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class ReorderedPowerOf2 {
// Function to determine if the number can be reordered to form a power of two
public boolean reorderedPowerOf2(int n) {
// Generate all powers of 2 within the range of 32-bit integers
Set<String> powerOf2Digits = new HashSet<>();
for (int i = 0; i < 31; i++) {
int powerOf2 = 1 << i;
char[] powerDigits = Integer.toString(powerOf2).toCharArray();
Arrays.sort(powerDigits);
powerOf2Digits.add(new String(powerDigits));
}
// Sort the digits of the input number
char[] numberDigits = Integer.toString(n).toCharArray();
Arrays.sort(numberDigits);
String sortedNumberDigits = new String(numberDigits);
// Check if the sorted input number digits match any of the power of 2 sorted digits
return powerOf2Digits.contains(sortedNumberDigits);
}
public static void main(String[] args) {
ReorderedPowerOf2 solution = new ReorderedPowerOf2();
System.out.println(solution.reorderedPowerOf2(128)); // True
System.out.println(solution.reorderedPowerOf2(256)); // True
System.out.println(solution.reorderedPowerOf2(10)); // False
}
}
n is ( O(m \log m) ), where ( m ) is the number of digits in n.Overall, the time complexity is efficiently handled and is dominated by the ( O(1) ) membership check in the set, making the approach very feasible for typical input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?