Skip to main content
Back to problems
#869
Medium Algorithms

Reordered power of 2

Hash Table Math Sorting Counting Enumeration
66.0% acceptance
Feb 22, 2026
2541
499
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.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
/*
 * 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
 */

fn sorted_digits(mut n: i32) -> [u8; 10] {
  let mut cnt = [0u8; 10];
  while n > 0 { cnt[(n % 10) as usize] += 1; n /= 10; }
  cnt
}

impl Solution {
  pub fn reordered_power_of2(n: i32) -> bool {
    let target = sorted_digits(n);
    let mut p = 1i32;
    for _ in 0..31 {
      if sorted_digits(p) == target { return true; }
      p = p.saturating_mul(2);
    }
    false
  }
}