📜  求k为2的幂且总和为N |的数字。套装1

📅  最后修改于: 2021-05-04 09:23:01             🧑  作者: Mango

给定两个数字N和K。任务是打印K个2的幂,并且它们的和为N。如果不可能,则打印-1。

例子:

Input: N = 9, K = 4
Output: 4 2 2 1
4 + 2 + 2 + 1 = 9 

Input: N = 4, K = 5
Output: -1 

方法:可以使用以下算法解决上述问题:

  • 如果K小于N中的设置位数或大于N,则不可能。
  • 将2的幂在设置的位插入优先级队列。
  • 在优先级队列中进行迭代,直到获得K个元素, pop()最顶部的元素以及
  • 推()

    element / 2两次进入优先级队列。

  • 一旦达到K个元素,就将它们打印出来。

下面是上述方法的实现:

C++
// CPP program to find k numbers that 
// are power of 2 and have sum equal 
// to N
#include 
using namespace std;
  
// function to print numbers
void printNum(int n, int k)
{
    // Count the number of set bits
    int x = __builtin_popcount(n);
  
    // Not-possible condition
    if (k < x || k > n) {
        cout << "-1";
        return;
    }
  
    // Stores the number
    priority_queue pq;
  
    // Get the set bits
    int two = 1;
    while (n) {
        if (n & 1) {
            pq.push(two);
        }
  
        two = two * 2;
        n = n >> 1;
    }
  
    // Iterate till we get K elements
    while (pq.size() < k) {
  
        // Get the topmost element
        int el = pq.top();
        pq.pop();
  
        // Push the elements/2 into 
        // priority queue
        pq.push(el / 2);
        pq.push(el / 2);
    }
  
    // Print all elements
    int ind = 0;
    while (ind < k) {
        cout << pq.top() << " ";
        pq.pop();
        ind++;
    }
}
  
// Driver Code
int main()
{
    int n = 9, k = 4;
    printNum(n, k);
    return 0;
}


Java
// Java program to find k numbers that 
// are power of 2 and have sum equal 
// to N 
import java.io.*;
import java.util.*;
  
class GFG 
{
  
    // function to print numbers
    static void printNum(int n, int k)
    {
  
        // Count the number of set bits
        String str = Integer.toBinaryString(n);
        int x = 0;
        for (int i = 0; i < str.length(); i++)
            if (str.charAt(i) == '1')
                x++;
  
        // Not-possible condition
        if (k < x || k > n)
        {
            System.out.println("-1");
            return;
        }
  
        // Stores the number
        PriorityQueue pq = 
        new PriorityQueue<>(Comparator.reverseOrder());
  
        // Get the set bits
        int two = 1;
        while (n > 0) 
        {
            if ((n & 1) == 1)
                pq.add(two);
            two *= 2;
            n = n >> 1;
        }
  
        // Iterate till we get K elements
        while (pq.size() < k)
        {
  
            // Get the topmost element
            int el = pq.poll();
  
            // Push the elements/2 into
            // priority queue
            pq.add(el / 2);
            pq.add(el / 2);
        }
  
        // Print all elements
        int ind = 0;
        while (ind < k) 
        {
            System.out.print(pq.poll() + " ");
            ind++;
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int n = 9, k = 4;
        printNum(n, k);
    }
}
  
// This code is contributed by
// sanjeev2552


Python
# Python program to find k numbers that 
# are power of 2 and have sum equal 
# to N 
  
# function to prnumbers 
def printNum(n, k):
      
    # Count the number of set bits 
    x = 0
    m = n
    while (m): 
        x += m & 1
        m >>= 1
      
    # Not-possible condition 
    if k < x or k > n:
        print("-1")
        return
      
    # Stores the number 
    pq = []
      
    # Get the set bits 
    two = 1
    while (n):
        if (n & 1):
            pq.append(two) 
              
        two = two * 2
        n = n >> 1
          
    # Iterate till we get K elements 
    while (len(pq) < k):
      
        # Get the topmost element 
        el = pq[-1]
        pq.pop()
  
        # append the elements/2 into 
        # priority queue 
        pq.append(el // 2) 
        pq.append(el // 2)
          
    # Prall elements 
    ind = 0
    pq.sort()
    while (ind < k):
        print(pq[-1], end = " ")
        pq.pop()
        ind += 1
  
# Driver Code 
n = 9
k = 4
printNum(n, k) 
  
# This code is contributed by SHUBHAMSINGH10


输出:
4 2 2 1

将n表示为两个|的正好k次幂之和。套装2