📌  相关文章
📜  计数将 N 表示为不超过 N 的不同整数的异或的方法

📅  最后修改于: 2022-05-13 01:56:05.437000             🧑  作者: Mango

计数将 N 表示为不超过 N 的不同整数的异或的方法

给定一个正整数N ,任务是找到将N表示为小于或等于N的不同正整数的按位异或的方法数。

例子:

朴素方法:解决问题的最简单方法是找到前N个自然数的所有子集,并对那些具有按位异或值N的子集进行计数。检查所有子集后,打印获得的计数的总值。

时间复杂度: O(N * 2 N )
辅助空间: O(1)

有效方法:上述方法可以通过观察将N表示为不同正整数的按位异或的方法数由下式给出2^{\lfloor N - \log_2(N + 1) \rfloor}        .

下面是上述方法的实现:

C++
// C++ program for the above approach
#include
using namespace std;
 
// Function to count number of ways
// to represent N as the Bitwise
// XOR of distinct integers
void countXorPartition(int N)
{
     
    // Count number of subsets using
    // above-mentioned formula
    double a = pow(2, floor(N - log(N + 1) /
                                log(2)));
     
    // Print the resultant count
    cout << a;
}
   
// Driver Code
int main()
{
    int N = 5;
     
    countXorPartition(N);
}
 
// This code is contributed by SURENDRA_GANGWAR


Java
// java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to count number of ways
// to represent N as the Bitwise
// XOR of distinct integers
static void countXorPartition(int N)
{
     
    // Count number of subsets using
    // above-mentioned formula
    double a = Math.pow(2, (int)(N - Math.log(N + 1) /
                                Math.log(2)));
     
    // Print the resultant count
    System.out.print(a);
}
   
// Driver Code
public static void main(String[] args)
{
    int N = 5;  
    countXorPartition(N);
}
}
 
// This code is contributed by shivanisinghss2110


Python
# Python program for the above approach
 
from math import * 
 
# Function to count number of ways
# to represent N as the Bitwise
# XOR of distinct integers
def countXorPartition(N):
   
  # Count number of subsets using
  # above-mentioned formula
  a = 2**floor(N - log(N + 1)/log(2))
   
  # Print the resultant count
  print(int(a))
 
# Driver Code
 
N = 5
countXorPartition(N)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count number of ways
// to represent N as the Bitwise
// XOR of distinct integers
static void countXorPartition(int N)
{
     
    // Count number of subsets using
    // above-mentioned formula
    double a = Math.Pow(2, (int)(N - Math.Log(N + 1) /
                                Math.Log(2)));
     
    // Print the resultant count
    Console.Write(a);
}
   
// Driver Code
public static void Main()
{
    int N = 5;  
    countXorPartition(N);
}
}
 
// This code is contributed by ipg2016107.


Javascript


输出:
4

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