📜  使用位掩码将2的幂乘以所需的总和

📅  最后修改于: 2021-05-06 08:03:04             🧑  作者: Mango

给定整数N ,任务是要找到数字,将其乘以2的幂后,将得到整数N。

例子:

方法:

  • 由于每个数字都可以表示为2的幂的和,因此当在N的二进制表示形式中设置i位时,任务是打印每个i
  • 为了检查i位是否已设置,我们只需要检查:

下面是上述方法的实现。

C++
// C++ Program to split N
// into numbers which when
// added after being raised
// to the power of 2 gives N
  
#include 
using namespace std;
  
// Function to print the numbers
// which raised to power of 2
// adds up to N
void PowerOfTwo(long long N)
{
    for (int i = 0; i < 64; i++) {
        long long x = 1;
  
        // Checking if i-th bit is
        // set in N or not by
        // shifting 1 i bits to
        // the left and performing
        // AND with N
        if (N & (x << i))
            cout << i << " ";
    }
}
  
// Driver Code
int main()
{
  
    long long N = 12345;
    PowerOfTwo(N);
  
    return 0;
}


Java
// Java Program to split N
// into numbers which when
// added after being raised
// to the power of 2 gives N
class GFG{
  
// Function to print the numbers
// which raised to power of 2
// adds up to N
static void PowerOfTwo(long N)
{
    for (int i = 0; i < 64; i++) 
    {
        long x = 1;
  
        // Checking if i-th bit is
        // set in N or not by
        // shifting 1 i bits to
        // the left and performing
        // AND with N
        if ((N & (x << i)) > 0)
            System.out.print(i + " ");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    long N = 12345;
    PowerOfTwo(N);
}
}
  
// This code is contributed by Amit Katiyar


Python3
# Python3 program to split N
# into numbers which when
# added after being raised
# to the power of 2 gives N
  
# Function to print the numbers
# which raised to power of 2
# adds up to N
def PowerOfTwo(N):
  
    for i in range(0, 64): 
        x = 1
          
        # Checking if i-th bit is
        # set in N or not by
        # shifting 1 i bits to
        # the left and performing
        # AND with N
        if (N & (x << i)) > 0:
            print(i, end = " ")
          
# Driver Code 
if __name__ == "__main__": 
      
    # Given number
    N = 12345;
  
    # Function call
    PowerOfTwo(N)
  
# This code is contributed by rock_cool


C#
// C# Program to split N
// into numbers which when
// added after being raised
// to the power of 2 gives N
using System;
class GFG{
  
// Function to print the numbers
// which raised to power of 2
// adds up to N
static void PowerOfTwo(long N)
{
    for (int i = 0; i < 64; i++) 
    {
        long x = 1;
  
        // Checking if i-th bit is
        // set in N or not by
        // shifting 1 i bits to
        // the left and performing
        // AND with N
        if ((N & (x << i)) > 0)
            Console.Write(i + " ");
    }
}
  
// Driver Code
public static void Main()
{
    long N = 12345;
    PowerOfTwo(N);
}
}
  
// This code is contributed by Nidhi_biet


输出:
0 3 4 5 12 13

时间复杂度: O(log N)
空间复杂度: O(1)

有关替代方法,请参考2的幂以求和