Created
August 10, 2025 17:40
-
-
Save tatsuyax25/be761d5b3d52dcfa759f4f129881e7c5 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} n | |
* @return {boolean} | |
*/ | |
var reorderedPowerOf2 = function(n) { | |
// Convert the number to an array of digit characters | |
const digits = n.toString().split(''); | |
// Helper function to generate all unique permutations of the digits | |
function getPermutations(arr) { | |
const results = []; | |
function backtrack(path, used) { | |
// Base case: if path is complete, add to results | |
if (path.length === arr.length) { | |
// Skip permutations with leading zero | |
if (path[0] !== '0') { | |
results.push([...path]); | |
} | |
return; | |
} | |
for (let i = 0; i < arr.length; i++) { | |
// Skip used digits | |
if (used[i]) continue; | |
// Skip duplicates (important for repeated digits) | |
if (i > 0 && arr[i] === arr[i - 1] && !used[i - 1]) continue; | |
used[i] = true; | |
path.push(arr[i]); | |
backtrack(path, used); | |
path.pop(); | |
used[i] = false; | |
} | |
} | |
// Sort to handle duplicates properly | |
arr.sort(); | |
backtrack([], Array(arr.length).fill(false)); | |
return results; | |
} | |
// Helper function to check if a number is a power of two | |
function isPowerOfTwo(x) { | |
// Bitwise trick: only powers of two have a single bit set | |
return (x & (x - 1)) === 0 && x !== 0; | |
} | |
// Generate all valid permutations of the digits | |
const validPermutations = getPermutations(digits); | |
// Check each permutation to see if it's a power of two | |
for (let perm of validPermutations) { | |
const num = parseInt(perm.join(''), 10); | |
if (isPowerOfTwo(num)) return true; | |
} | |
// If none match, return false | |
return false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment