Leetcode•Dec 03, 2026

Reordered Power of 2

Hazrat Ali

Leetcode

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

Solution
var reorderedPowerOf2 = function(n) {
    function countDigits(num) {
        const count = Array(10).fill(0);

        for (let digit of String(num)) {
            count[Number(digit)]++;
        }

        return count.join('');
    }

    const target = countDigits(n);

    for (let i = 0; i < 31; i++) {
        const power = 2 ** i;

        if (countDigits(power) === target) {
            return true;
        }
    }

    return false;
};
 

Comments