📌  相关文章
📜  将N表示为两个|的正好K次幂之和。套装3

📅  最后修改于: 2021-05-25 03:20:20             🧑  作者: Mango

给定两个整数NK ,任务是确定是否有可能将N表示为K2次幂的和。如果可能,然后打印K个正整数,使它们为2的幂,并且它们的总和恰好等于N。否则,打印“不可能” 。如果存在多个答案,请打印任何答案。

例子:

基于优先级队列的方法:请参考本文以使用优先级队列解决问题。

递归方法:请参阅本文以使用递归解决问题。

替代方法:该想法是使用贪婪方法来解决此问题。步骤如下:

  • 初始化一个整数,例如num = 31 ,并初始化一个整数向量,例如res ,以存储K的2的幂。
  • 检查N中的位数是否大于KN小于K,然后打印“不可能”。
  • num≥0且K> 0时进行迭代
    • 检查N – 2 num是否小于K – 1 。如果发现为真,则将num减1并继续。
    • 否则,将K减1,将N2 num,然后将num推入向量res
  • 最后,打印矢量res

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find K numbers with
// sum N that are powers of 2
void nAsKPowersOfTwo(int N, int K)
{
    // Count the number of set bits
    int x = __builtin_popcount(N);
 
    // Not-possible condition
    if (K < x || K > N) {
        cout << "Impossible";
        return;
    }
 
    int num = 31;
 
    // To store K numbers
    // which are powers of 2
    vector res;
 
    // Traverse while num >= 0
    while (num >= 0 && K) {
 
        // Calculate current bit value
        int val = pow(2, num);
 
        // Check if remaining N
        // can be reprsented as
        // K-1 numbers that are
        // power of 2
        if (N - val < K - 1) {
 
            // Decrement num by one
            --num;
            continue;
        }
 
        // Decrement K by one
        --K;
 
        // Decrement N by val
        N -= val;
 
        // Push the num in the
        // vector res
        res.push_back(num);
    }
 
    // Print the vector res
    for (auto x : res)
        cout << pow(2, x) << " ";
}
 
// Driver Code
int main()
{
    // Given N & K
    int N = 7, K = 4;
 
    // Function Call
    nAsKPowersOfTwo(N, K);
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to find K numbers with
// sum N that are powers of 2
static void nAsKPowersOfTwo(int N, int K)
{
   
    // Count the number of set bits
    int x = Integer.bitCount(N);
 
    // Not-possible condition
    if (K < x || K > N)
    {
        System.out.print("Impossible");
        return;
    }
 
    int num = 31;
 
    // To store K numbers
    // which are powers of 2
    Vector res = new Vector();
 
    // Traverse while num >= 0
    while (num >= 0 && K > 0)
    {
 
        // Calculate current bit value
        int val = (int) Math.pow(2, num);
 
        // Check if remaining N
        // can be reprsented as
        // K-1 numbers that are
        // power of 2
        if (N - val < K - 1)
        {
 
            // Decrement num by one
            --num;
            continue;
        }
 
        // Decrement K by one
        --K;
 
        // Decrement N by val
        N -= val;
 
        // Push the num in the
        // vector res
        res.add(num);
    }
 
    // Print the vector res
    for (int i : res)
        System.out.print((int)Math.pow(2, i)+ " ");
}
 
// Driver Code
public static void main(String[] args)
{
    // Given N & K
    int N = 7, K = 4;
 
    // Function Call
    nAsKPowersOfTwo(N, K);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to find K numbers with
# sum N that are powers of 2
def nAsKPowersOfTwo(N, K):
     
    # Count the number of set bits
    x = bin(N).count('1')
 
    # Not-possible condition
    if (K < x or K > N):
        cout << "Impossible"
        return
    num = 31
 
    # To store K numbers
    # which are powers of 2
    res = []
 
    # Traverse while num >= 0
    while (num >= 0 and K):
 
        # Calculate current bit value
        val = pow(2, num)
 
        # Check if remaining N
        # can be reprsented as
        # K-1 numbers that are
        # power of 2
        if (N - val < K - 1):
 
            # Decrement num by one
            num -= 1
            continue
 
        # Decrement K by one
        K -= 1
 
        # Decrement N by val
        N -= val
 
        # Push the num in the
        # vector res
        res.append(num)
 
    # Prthe vector res
    for x in res:
        print(pow(2, x), end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given N & K
    N, K = 7, 4
 
    # Function Call
    nAsKPowersOfTwo(N, K)
 
# This code is contributed mohit kumar 29.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find K numbers with
// sum N that are powers of 2
static void nAsKPowersOfTwo(int N, int K)
{
   
    // Count the number of set bits
    int x = countSetBits(N);
 
    // Not-possible condition
    if (K < x || K > N)
    {
        Console.Write("Impossible");
        return;
    }
 
    int num = 31;
 
    // To store K numbers
    // which are powers of 2
    List res = new List();
 
    // Traverse while num >= 0
    while (num >= 0 && K > 0)
    {
 
        // Calculate current bit value
        int val = (int) Math.Pow(2, num);
 
        // Check if remaining N
        // can be reprsented as
        // K-1 numbers that are
        // power of 2
        if (N - val < K - 1)
        {
 
            // Decrement num by one
            --num;
            continue;
        }
 
        // Decrement K by one
        --K;
 
        // Decrement N by val
        N -= val;
 
        // Push the num in the
        // vector res
        res.Add(num);
    }
 
    // Print the vector res
    foreach (int i in res)
        Console.Write((int)Math.Pow(2, i)+ " ");
}
static int countSetBits(long x)
{
    int setBits = 0;
    while (x != 0)
    {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
   
// Driver Code
public static void Main(String[] args)
{
    // Given N & K
    int N = 7, K = 4;
 
    // Function Call
    nAsKPowersOfTwo(N, K);
}
}
 
// This code is contributed by shikhasingrajput


输出:
4 1 1 1

时间复杂度: O(32)
辅助空间: O(1)