Reorder digits of a given number to make it a power of 2
Last Updated :
29 Dec, 2022
Given a positive integer N, the task is to rearrange the digits of the given integer such that the integer becomes a power of 2. If more than one solution exists, then print the smallest possible integer without leading 0. Otherwise, print -1.
Examples:
Input: N = 460
Output: 64
Explanation:
64 is a power of 2, the required output is 64.
Input: 36
Output: -1
Explanation:
Possible rearrangement of the integer are { 36, 63 }.
Therefore, the required output is -1.
Approach: The idea is to generate all permutations of the digits of the given integer. For each permutation, check if the integer is a power of 2 or not. If found to be true then print the integer. Otherwise, print -1. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to rearrange the digits of N
// such that N become power of 2
int reorderedPowerOf2(int n)
{
// Stores digits of N
string str = to_string(n);
// Sort the string
// ascending order
sort(str.begin(), str.end());
// Stores count of digits in N
int sz = str.length();
// Generate all permutation and check if
// the permutation if power of 2 or not
do {
// Update n
n = stoi(str);
// If n is power of 2
if (n && !(n & (n - 1))) {
return n;
}
} while (next_permutation(str.begin(), str.end()));
return -1;
}
// Driver Code
int main()
{
int n = 460;
cout << reorderedPowerOf2(n);
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG {
static void swap(char[] chars, int i, int j)
{
char ch = chars[i];
chars[i] = chars[j];
chars[j] = ch;
}
static void reverse(char[] chars, int start)
{
for (int i = start, j = chars.length - 1; i < j;
i++, j--) {
swap(chars, i, j);
}
}
// Function to find lexicographically next permutations
// of a string. It returns true if the string could be
// rearranged as a lexicographically greater permutation
// else it returns false
static boolean next_permutation(char[] chars)
{
// Find largest index i such
// that chars[i - 1] is less than chars[i]
int i = chars.length - 1;
while (chars[i - 1] >= chars[i]) {
// if i is first index of the string,
// that means we are already at
// highest possible permutation i.e.
// string is sorted in desc order
if (--i == 0) {
return false;
}
}
// if we reach here, substring chars[i..n)
// is sorted in descending order
// i.e. chars[i-1] < chars[i] >= chars[i+1] >=
// chars[i+2] >= ... >= chars[n-1]
// Find highest index j to the right of index i such
// that chars[j] > chars[i–1]
int j = chars.length - 1;
while (j > i && chars[j] <= chars[i - 1]) {
j--;
}
// swap characters at index i-1 with index j
swap(chars, i - 1, j);
// reverse the substring chars[i..n) and return true
reverse(chars, i);
return true;
}
// Function to rearrange the digits of N
// such that N become power of 2
static int reorderedPowerOf2(int n)
{
// Stores digits of N
String str = Integer.toString(n);
char[] Str = str.toCharArray();
// Sort the string
// ascending order
Arrays.sort(Str);
// Stores count of digits in N
int sz = Str.length;
// Generate all permutation and check if
// the permutation if power of 2 or not
do {
// Update n
n = Integer.parseInt(new String(Str));
// If n is power of 2
if (n > 0 && ((n & (n - 1)) == 0)) {
return n;
}
} while (next_permutation(Str));
return -1;
}
// Driver code
public static void main(String[] args)
{
int n = 460;
System.out.print(reorderedPowerOf2(n));
}
}
// This code is contributed by Dharanendra L V.
Python3
# python program to implement
# the above approach
def next_permutation():
global a
i = len(a) - 2
while not (i < 0 or int(a[i]) < int(a[i + 1])):
i -= 1
if i < 0:
return False
# else
j = len(a) - 1
while not (int(a[j]) > int(a[i])):
j -= 1
a[i], a[j] = a[j], a[i] # swap
# reverse elements from position i+1 till the end of the sequence
a[i + 1:] = reversed(a[i + 1:])
return True
# Function to rearrange the digits of N
# such that N become power of 2
def reorderedPowerOf2(n):
global a
# Sort the string
# ascending order
a = sorted(a)
# Stores count of digits in N
sz = len(a)
# Generate all permutation and check if
# the permutation if power of 2 or not
while True:
# Update n
n = int("".join(a))
# If n is power of 2
if (n and not (n & (n - 1))):
return n
if not next_permutation():
break
return -1
# Driver Code
if __name__ == '__main__':
n = 460
a = [i for i in str(n)]
print(reorderedPowerOf2(n))
# This code is contributed by mohit kumar 29
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
static void swap(char[] chars, int i, int j)
{
char ch = chars[i];
chars[i] = chars[j];
chars[j] = ch;
}
static void reverse(char[] chars, int start)
{
for (int i = start, j = chars.Length - 1; i < j;
i++, j--) {
swap(chars, i, j);
}
}
// Function to find lexicographically next permutations
// of a string. It returns true if the string could be
// rearranged as a lexicographically greater permutation
// else it returns false
static bool next_permutation(char[] chars)
{
// Find largest index i such
// that chars[i - 1] is less than chars[i]
int i = chars.Length - 1;
while (chars[i - 1] >= chars[i]) {
// if i is first index of the string,
// that means we are already at
// highest possible permutation i.e.
// string is sorted in desc order
if (--i == 0) {
return false;
}
}
// if we reach here, substring chars[i..n)
// is sorted in descending order
// i.e. chars[i-1] < chars[i] >= chars[i+1] >=
// chars[i+2] >= ... >= chars[n-1]
// Find highest index j to the right of index i such
// that chars[j] > chars[i–1]
int j = chars.Length - 1;
while (j > i && chars[j] <= chars[i - 1]) {
j--;
}
// swap characters at index i-1 with index j
swap(chars, i - 1, j);
// reverse the substring chars[i..n) and return true
reverse(chars, i);
return true;
}
// Function to rearrange the digits of N
// such that N become power of 2
static int reorderedPowerOf2(int n)
{
// Stores digits of N
string str = n.ToString();
char[] Str = str.ToCharArray();
// Sort the string
// ascending order
Array.Sort(Str);
// Stores count of digits in N
int sz = Str.Length;
// Generate all permutation and check if
// the permutation if power of 2 or not
do {
// Update n
n = Convert.ToInt32(new string(Str));
// If n is power of 2
if (n > 0 && ((n & (n - 1)) == 0)) {
return n;
}
} while (next_permutation(Str));
return -1;
}
// Driver code
static void Main()
{
int n = 460;
Console.WriteLine(reorderedPowerOf2(n));
}
}
// This code is contributed by divyeshrabadiya07.
JavaScript
<script>
// JavaScript program to implement
// the above approach
function swap(chars,i,j)
{
let ch = chars[i];
chars[i] = chars[j];
chars[j] = ch;
}
function reverse(chars,start)
{
for (let i = start, j = chars.length - 1; i < j;
i++, j--) {
swap(chars, i, j);
}
}
// Function to find lexicographically next permutations
// of a string. It returns true if the string could be
// rearranged as a lexicographically greater permutation
// else it returns false
function next_permutation(chars)
{
// Find largest index i such
// that chars[i - 1] is less than chars[i]
let i = chars.length - 1;
while (chars[i - 1] >= chars[i]) {
// if i is first index of the string,
// that means we are already at
// highest possible permutation i.e.
// string is sorted in desc order
if (--i == 0) {
return false;
}
}
// if we reach here, substring chars[i..n)
// is sorted in descending order
// i.e. chars[i-1] < chars[i] >= chars[i+1] >=
// chars[i+2] >= ... >= chars[n-1]
// Find highest index j to the right of index i such
// that chars[j] > chars[i–1]
let j = chars.length - 1;
while (j > i && chars[j] <= chars[i - 1]) {
j--;
}
// swap characters at index i-1 with index j
swap(chars, i - 1, j);
// reverse the substring chars[i..n) and return true
reverse(chars, i);
return true;
}
// Function to rearrange the digits of N
// such that N become power of 2
function reorderedPowerOf2(n)
{
// Stores digits of N
let str = n.toString();
let Str = str.split("");
// Sort the string
// ascending order
Str.sort();
// Stores count of digits in N
let sz = Str.length;
// Generate all permutation and check if
// the permutation if power of 2 or not
do {
// Update n
n = parseInt((Str).join(""));
// If n is power of 2
if (n > 0 && ((n & (n - 1)) == 0)) {
return n;
}
} while (next_permutation(Str));
return -1;
}
// Driver code
let n = 460;
document.write(reorderedPowerOf2(n));
// This code is contributed by patel2127
</script>
Time Complexity: O(log10N * (log10N)!)
Auxiliary Space: O(log10N)
Approach 2:
We will create a digit array which stores the digit count of the given number, and we will iterate through powers of 2 and check if any of the digitcount array matches with the given numbers digitcount array.
Below is the implementation of the approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
vector<int> digitarr(int n)
{
vector<int> res(10); // stores the digit count of n
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n /= 10;
}
return res;
}
int reorderedPowerOf2(int N)
{
vector<int> arr = digitarr(N);
// N is the given number
// arr have the digit count of N
for (int i = 0; i < 31; i++)
{
// check if arr matches with any digitcount
// array of 2^i
vector<int> arr1 = digitarr(1 << i);
if (arr == arr1)
return (int)pow(2, i);
}
return -1;
}
// Driver code
int main()
{
int n = 460;
cout << reorderedPowerOf2(n);
}
// This code is contributed by phasing17.
Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG {
public static int reorderedPowerOf2(int N)
{
int[] arr = digitarr(N);
// N is the given number
// arr have the digit count of N
for (int i = 0; i < 31; i++) {
// check if arr matches with any digitcount
// array of 2^i
if (Arrays.equals(arr, digitarr(1 << i)))
return (int)Math.pow(2, i);
}
return -1;
}
public static int[] digitarr(int n)
{
int[] res
= new int[10]; // stores the digit count of n
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n /= 10;
}
return res;
}
// Driver code
public static void main(String[] args)
{
int n = 460;
System.out.print(reorderedPowerOf2(n));
}
}
Python3
# Python3 program to implement
# the above approach
def reorderedPowerOf2(N):
arr = digitarr(N)
# N is the given number
# arr have the digit count of N
for i in range(31):
# check if arr matches with any digitcount
# array of 2^i
if (arr == digitarr(1 << i)):
return pow(2, i)
return -1
def digitarr(n):
res = [0] * 10 # stores the digit count of n
while (n > 0):
if (n % 10 != 0):
res[n % 10] += 1
n = int(n / 10)
return res
# Driver code
n = 460
print(reorderedPowerOf2(n))
# This code is contributed by phasing17.
C#
// C# program to implement
// the above approach
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
public static int reorderedPowerOf2(int N)
{
int[] arr = digitarr(N);
// N is the given number
// arr have the digit count of N
for (int i = 0; i < 31; i++) {
// check if arr matches with any digitcount
// array of 2^i
if (Enumerable.SequenceEqual(arr,
digitarr(1 << i)))
return (int)Math.Pow(2, i);
}
return -1;
}
public static int[] digitarr(int n)
{
int[] res
= new int[10]; // stores the digit count of n
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n /= 10;
}
return res;
}
// Driver code
public static void Main(string[] args)
{
int n = 460;
Console.WriteLine(reorderedPowerOf2(n));
}
}
// This code is contributed by phasing17.
JavaScript
// JS program to implement
// the above approach
function reorderedPowerOf2(N)
{
let arr = digitarr(N);
// N is the given number
// arr have the digit count of N
for (var i = 0; i < 31; i++)
{
// check if arr matches with any digitcount
// array of 2^i
if (arr.join(" ") == digitarr(1 << i).join(" ") )
return Math.pow(2, i);
}
return -1;
}
function digitarr( n)
{
let res = new Array(10).fill(0); // stores the digit count of n
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n = Math.floor(n / 10);
}
return res;
}
// Driver code
let n = 460;
console.log(reorderedPowerOf2(n));
// This code is contributed by phasing17.
Time Complexity: O(k*log(k)) where k=31
Auxiliary Space: O(1)
Similar Reads
Sum of digits of a given number to a given power
Given a number, we need to find the sum of all the digits of a number which we get after raising the number to a specified power.Examples: Input: number = 5, power = 4 Output: 13 Explanation: Raising 5 to the power 4 we get 625. Now adding all the digits = 6 + 2 + 5 Input: number = 9, power = 5 Outp
3 min read
Number of digits in 2 raised to power n
Let n be any power raised to base 2 i.e 2n. We are given the number n and our task is to find out the number of digits contained in the number 2n.Examples: Input : n = 5 Output : 2 Explanation : 2n = 32, which has only 2 digits. Input : n = 10 Output : 4 Explanation : 2n = 1024, which has only 4 dig
5 min read
Minimum number of distinct powers of 2 required to express a given binary number
Given a binary string S, the task is to find the minimum number of Powers of 2 required to express a S.Examples: Input: S = "111" Output: 2 Explanation: Two possible representations of "111" (= 7) using powers of 2 are: 20 + 21 + 22 = 1 + 2 + 4 = 7 23 - 20 = 8 - 1 = 7 Therefore, the minimum powers o
6 min read
Find whether a given number is a power of 4 or not
Given an integer n, find whether it is a power of 4 or not. Example : Input : 16Output : 16 is a power of 4Input : 20Output : 20 is not a power of 4Method 1: Using the in-built log method: Take log of given number to the base 4, and then raise 4 to this result. If the output is equal to n, then give
15+ min read
Check if given number is a power of d where d is a power of 2
Given an integer n, find whether it is a power of d or not, where d is itself a power of 2.Examples: Input : n = 256, d = 16 Output : Yes Input : n = 32, d = 16 Output : No Method 1 Take log of the given number on base d, and if we get an integer then number is power of d. C++ // CPP program to find
9 min read
Highest power of two that divides a given number
Given a number n, find the highest power of 2 that divides n.Examples: Input : n = 48 Output : 16 Highest power of 2 that divides 48 is 16.Input : n = 5 Output : 1 Highest power of 2 that divides 5 is 1. A simple solution is to try all powers of 2 one by one starting from 1, then 2, then 4 and so on
5 min read
Program to find whether a given number is power of 2
Given a positive integer n, the task is to find if it is a power of 2 or not.Examples: Input : n = 16Output : YesExplanation: 24 = 16Input : n = 42Output : NoExplanation: 42 is not a power of 2Input : n = 1Output : YesExplanation: 20 = 1Approach 1: Using Log - O(1) time and O(1) spaceThe idea is to
12 min read
Highest power of 2 less than or equal to given number
Given a number n, find the highest power of 2 that is smaller than or equal to n. Examples : Input : n = 10 Output : 8 Input : n = 19 Output : 16 Input : n = 32 Output : 32Recommended PracticeFinding PositionTry It! A simple solution is to start checking from n and keep decrementing until we find a
15 min read
Remove repeated digits in a given number
Given an integer, remove consecutive repeated digits from it. Examples: Input: x = 12224 Output: 124 Input: x = 124422 Output: 1242 Input: x = 11332 Output: 132 We need to process all digits of n and remove consecutive representations. We can go through all digits by repeatedly dividing n with 10 an
5 min read
Highest power of a number that divides other number | Set - 2
Given two numbers N and M(M > 1), the task is to find the highest power of M that divides N. Examples: Input: N = 12, M = 2Output: 2Explanation: The powers of 2 which divide 12 are 1 and 2 (21 = 2 and 22 = 4 which both divide 12). The higher power is 2, hence consider 2. Input: N = 500, M = 5Outp
5 min read