869. Reordered Power of 2
Description
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
Solutions
Solution: Bit Manipulation
- Time complexity: O(1)
- Space complexity: O(1)
JavaScript
js
/**
* @param {number} n
* @return {boolean}
*/
const reorderedPowerOf2 = function (n) {
const counter = num => {
let result = 0;
while (num) {
result += Math.pow(10, num % 10);
num = Math.floor(num / 10);
}
return result;
};
const count = counter(n);
for (let index = 0; index < 30; index++) {
const num = 1 << index;
if (counter(num) === count) return true;
}
return false;
};