Skip to content
Related Articles

Related Articles

Reorder digits of a given number to make it a power of 2
  • Difficulty Level : Medium
  • Last Updated : 03 Feb, 2021

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
    a[i + 1:] = reversed(a[i + 1:])    # reverse elements from position i+1 till the end of the sequence
    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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Output: 

64

 

Time Complexity: O(log10N * (log10N)!) 
Auxiliary Space: O(log10N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :