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

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

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

例子:

方法:可以根据以下观察结果解决问题:

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

因此,要解决该问题,只需检查N是否为2的幂。如果发现错误,则打印“”。否则,打印“ No ”。

下面是上述方法的实现:

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


输出
YES


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