给定一个整数N ,任务是检查前N个自然数[1,N]是否存在任何排列,以使任意一对连续元素的按位与不等于0 。如果存在任何这样的排列,请打印“是” 。否则,打印“否” 。
例子:
Input : 5
Output: Yes
Explanation: Permutation {2, 3, 1, 5, 4} satisfies the condition.
Input: 4
Output: No
Explanation: Since Bitwise AND of 4 and 3 is equal to 0, they cannot be placed adjacently. Similarly 2 and 4, 1 and 2, 1 and 4 cannot be placed adjacently. Therefore, no such permutation exists.
方法:可以根据以下观察结果解决问题:
- 如果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)