📜  对给定数字的数字重新排序以使其为2的幂

📅  最后修改于: 2021-04-24 04:40:55             🧑  作者: Mango

给定正整数N ,任务是重新排列给定整数的数字,以使该整数成为2的幂。如果存在多个解决方案,则打印可能的最小整数而不以0开头。否则,打印-1

例子:

方法:想法是生成给定整数的所有数字排列。对于每个排列,请检查整数是否为2的幂。如果发现为真,则打印整数。否则,打印-1 。请按照以下步骤解决问题:

  • 将给定的整数转换为字符串,例如str
  • 按升序对字符串进行排序。
  • 生成字符串的所有可能排列。对于每个排列,请检查字符串的等效整数值是否为2的幂。如果发现是真实的,则打印数字。
  • 如果不存在整数的这种排列,则打印-1

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
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.


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


输出
64

时间复杂度: O(log 10 N *(log 10 N)!)
辅助空间: O(log 10 N)

方法二:

我们将创建一个数字数组,该数字数组存储给定数字的数字计数,并迭代2的幂,并检查是否有任何digitcount数组与给定数字digitcount数组匹配。

下面是该方法的实现:

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));
    }
}
输出
64