Reorder digits of a given number to make it a power of 2
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++
#include <bits/stdc++.h>
using namespace std;
int reorderedPowerOf2( int n)
{
string str = to_string(n);
sort(str.begin(), str.end());
int sz = str.length();
do {
n = stoi(str);
if (n && !(n & (n - 1))) {
return n;
}
} while (next_permutation(str.begin(), str.end()));
return -1;
}
int main()
{
int n = 460;
cout << reorderedPowerOf2(n);
return 0;
}
|
Java
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);
}
}
static boolean next_permutation( char [] chars)
{
int i = chars.length - 1 ;
while (chars[i - 1 ] >= chars[i]) {
if (--i == 0 ) {
return false ;
}
}
int j = chars.length - 1 ;
while (j > i && chars[j] <= chars[i - 1 ]) {
j--;
}
swap(chars, i - 1 , j);
reverse(chars, i);
return true ;
}
static int reorderedPowerOf2( int n)
{
String str = Integer.toString(n);
char [] Str = str.toCharArray();
Arrays.sort(Str);
int sz = Str.length;
do {
n = Integer.parseInt( new String(Str));
if (n > 0 && ((n & (n - 1 )) == 0 )) {
return n;
}
} while (next_permutation(Str));
return - 1 ;
}
public static void main(String[] args)
{
int n = 460 ;
System.out.print(reorderedPowerOf2(n));
}
}
|
Python3
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
j = len (a) - 1
while not ( int (a[j]) > int (a[i])):
j - = 1
a[i], a[j] = a[j], a[i]
a[i + 1 :] = reversed (a[i + 1 :])
return True
def reorderedPowerOf2(n):
global a
a = sorted (a)
sz = len (a)
while True :
n = int ("".join(a))
if (n and not (n & (n - 1 ))):
return n
if not next_permutation():
break
return - 1
if __name__ = = '__main__' :
n = 460
a = [i for i in str (n)]
print (reorderedPowerOf2(n))
|
C#
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);
}
}
static bool next_permutation( char [] chars)
{
int i = chars.Length - 1;
while (chars[i - 1] >= chars[i]) {
if (--i == 0) {
return false ;
}
}
int j = chars.Length - 1;
while (j > i && chars[j] <= chars[i - 1]) {
j--;
}
swap(chars, i - 1, j);
reverse(chars, i);
return true ;
}
static int reorderedPowerOf2( int n)
{
string str = n.ToString();
char [] Str = str.ToCharArray();
Array.Sort(Str);
int sz = Str.Length;
do {
n = Convert.ToInt32( new string (Str));
if (n > 0 && ((n & (n - 1)) == 0)) {
return n;
}
} while (next_permutation(Str));
return -1;
}
static void Main()
{
int n = 460;
Console.WriteLine(reorderedPowerOf2(n));
}
}
|
Javascript
<script>
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 next_permutation(chars)
{
let i = chars.length - 1;
while (chars[i - 1] >= chars[i]) {
if (--i == 0) {
return false ;
}
}
let j = chars.length - 1;
while (j > i && chars[j] <= chars[i - 1]) {
j--;
}
swap(chars, i - 1, j);
reverse(chars, i);
return true ;
}
function reorderedPowerOf2(n)
{
let str = n.toString();
let Str = str.split( "" );
Str.sort();
let sz = Str.length;
do {
n = parseInt((Str).join( "" ));
if (n > 0 && ((n & (n - 1)) == 0)) {
return n;
}
} while (next_permutation(Str));
return -1;
}
let n = 460;
document.write(reorderedPowerOf2(n));
</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++
#include <bits/stdc++.h>
using namespace std;
vector< int > digitarr( int n)
{
vector< int > res(10);
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n /= 10;
}
return res;
}
int reorderedPowerOf2( int N)
{
vector< int > arr = digitarr(N);
for ( int i = 0; i < 31; i++)
{
vector< int > arr1 = digitarr(1 << i);
if (arr == arr1)
return ( int ) pow (2, i);
}
return -1;
}
int main()
{
int n = 460;
cout << reorderedPowerOf2(n);
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int reorderedPowerOf2( int N)
{
int [] arr = digitarr(N);
for ( int i = 0 ; i < 31 ; 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 ];
while (n > 0 ) {
if (n % 10 != 0 ) {
res[n % 10 ]++;
}
n /= 10 ;
}
return res;
}
public static void main(String[] args)
{
int n = 460 ;
System.out.print(reorderedPowerOf2(n));
}
}
|
Python3
def reorderedPowerOf2(N):
arr = digitarr(N)
for i in range ( 31 ):
if (arr = = digitarr( 1 << i)):
return pow ( 2 , i)
return - 1
def digitarr(n):
res = [ 0 ] * 10
while (n > 0 ):
if (n % 10 ! = 0 ):
res[n % 10 ] + = 1
n = int (n / 10 )
return res
n = 460
print (reorderedPowerOf2(n))
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
public static int reorderedPowerOf2( int N)
{
int [] arr = digitarr(N);
for ( int i = 0; i < 31; 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];
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n /= 10;
}
return res;
}
public static void Main( string [] args)
{
int n = 460;
Console.WriteLine(reorderedPowerOf2(n));
}
}
|
Javascript
function reorderedPowerOf2(N)
{
let arr = digitarr(N);
for ( var i = 0; i < 31; 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);
while (n > 0) {
if (n % 10 != 0) {
res[n % 10]++;
}
n = Math.floor(n / 10);
}
return res;
}
let n = 460;
console.log(reorderedPowerOf2(n));
|
Time Complexity: O(k*log(k)) where k=31
Auxiliary Space: O(1)
Last Updated :
29 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...