Algorithm


Problem Name: 869. Reordered Power of 2

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

Code Examples

#1 Code Example with Java Programming

Code - Java Programming

start codi
class Solution {
  public boolean reorderedPowerOf2(int n) {
    int[] digitCount = count(n);
    for (int i = 0; i  <  31; i++) {
      if (Arrays.equals(digitCount, count(1 << i))) {
        return true;
      }
    }
    return false;
  }
  
  private int[] count(int n) {
    int[] result = new int[10];
    while (n > 0) {
      result[n % 10]++;
      n /= 10;
    }
    return result;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 1

Output

x
+
cmd
true

#2 Code Example with Javascript Programming

Code - Javascript Programming


const reorderedPowerOf2 = function(N) {
  const A = count(N);
  for (let i = 0; i  <  31; i++) {
    if (arrayEqual(A, count(1 << i))) return true;
  }
  return false;
};

function count(num) {
  const res = [];
  while (num > 0) {
    addOne(res, num % 10);
    num = parseInt(num / 10);
  }
  return res;
}
function addOne(arr, idx) {
  if (arr[idx]) {
    arr[idx] += 1;
    return;
  }
  arr[idx] = 1;
}
function arrayEqual(a1, a2) {
  return JSON.stringify(a1) === JSON.stringify(a2);
}

console.log(reorderedPowerOf2(1));
console.log(reorderedPowerOf2(10));
console.log(reorderedPowerOf2(16));
console.log(reorderedPowerOf2(24));
console.log(reorderedPowerOf2(46));
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 1

Output

x
+
cmd
true

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def reorderedPowerOf2(self, N):
        cnt = collections.Counter(str(N))
        return any(cnt == collections.Counter(str(1 << c)) for c in range(32))
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
#868 Leetcode Binary Gap Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#870 Leetcode Advantage Shuffle Solution in C, C++, Java, JavaScript, Python, C# Leetcode