📌  相关文章
📜  检查前 N 个自然数的排列是否存在相邻元素的按位与非零

📅  最后修改于: 2021-10-25 09:19:52             🧑  作者: Mango

给定一个整数N ,任务是检查前N 个自然数[1, N]是否存在任何排列,使得任何一对连续元素的按位与不等于0 。如果存在任何此类排列,请打印“是” 。否则,打印“否”

例子:

方法:该问题可以基于以下观察来解决:

  • 如果N是 2 的幂,则N & (N – 1)等于0 。因此,不存在可能的解决方案。
  • 否则,存在排列。

因此,要解决这个问题,只需检查N是否是2的幂。如果发现是假的,打印“”。否则,打印“”。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to check if a permutation
// of first N natural numbers exist
// with Bitwise AND of adjacent
// elements not equal to 0
void check(int n)
{
    // If n is a power of 2
    if ((n & n - 1) != 0)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
}
 
// Driver Code
int main()
{
 
    int n = 5;
    check(n);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class solution{
     
// Function to check if a
// permutation of first N
// natural numbers exist
// with Bitwise AND of adjacent
// elements not equal to 0
static void check(int n)
{
  // If n is a power of 2
  if ((n & n - 1) != 0)
    System.out.println("YES");
  else
    System.out.println("NO");
}
 
// Driver Code
public static void main(String args[])
{
  int n = 5;
  check(n);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Python3
# Python3 program to implement
# the above approach
 
# Function to check if a permutation
# of first N natural numbers exist
# with Bitwise AND of adjacent
# elements not equal to 0
def check(n):
     
    # If n is a power of 2
    if ((n & n - 1) != 0):
        print("YES")
    else:
        print("NO")
 
# Driver Code
if __name__ == '__main__':
     
    n = 5
     
    check(n)
 
# This code is contributed by bgangwar59


C#
// C# Program to implement
// the above approach
using System;
class solution{
     
// Function to check if a
// permutation of first N
// natural numbers exist
// with Bitwise AND of adjacent
// elements not equal to 0
static void check(int n)
{
  // If n is a power of 2
  if ((n & n - 1) != 0)
    Console.WriteLine("YES");
  else
    Console.WriteLine("NO");
}
 
// Driver Code
public static void Main(String []args)
{
  int n = 5;
  check(n);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
YES

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