给定正整数n 。问题是检查此整数是否在其二进制表示形式中具有备用模式。这里备用模式的装置,所述设置和取消位在正发生在替代顺序。例如-5具有替代图案,即101。
如果有其他图案,则打印“是”,否则为“否”。
注意: 0 例子 : 简单方法:本文已讨论了时间复杂度为O(n)的问题。 高效方法:以下是步骤: 输出 : Input : 10
Output : Yes
(10)10 = (1010)2, has an alternate pattern.
Input : 12
Output : No
(12)10 = (1100)2, does not have an alternate pattern.
C++
// C++ implementation to check if a number
// has bits in alternate pattern
#include
Java
// Java implementation to check if a
// number has bits in alternate pattern
class AlternateSetBits
{
// function to check if all the bits
// are set or not in the binary
// representation of 'n'
static boolean allBitsAreSet(int n)
{
// if true, then all bits are set
if (((n + 1) & n) == 0)
return true;
// else all bits are not set
return false;
}
// function to check if a number
// has bits in alternate pattern
static boolean bitsAreInAltOrder(int n)
{
int num = n ^ (n >>> 1);
// to check if all bits are set
// in 'num'
return allBitsAreSet(num);
}
// Driver Code
public static void main(String args[])
{
int n = 10;
if (bitsAreInAltOrder(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
/* This code is contributed by Danish Kaleem */
Python3
# Python implementation to check if a number
# has bits in alternate pattern
# function to check if all the bits are set or not
# in the binary representation of 'n'
def allBitsAreSet(n):
# if true, then all bits are set
if (((n + 1) & n) == 0):
return True;
# else all bits are not set
return False;
# function to check if a number
# has bits in alternate pattern
def bitsAreInAltOrder(n):
num = n ^ (n >> 1);
# to check if all bits are set
# in 'num'
return allBitsAreSet(num);
# Driver code
n = 10;
if (bitsAreInAltOrder(n)):
print("Yes");
else:
print("No");
# This code is contributed by PrinciRaj1992
C#
// C# implementation to check if a
// number has bits in alternate pattern
using System;
class GFG {
// function to check if all the bits
// are set or not in the binary
// representation of 'n'
static bool allBitsAreSet(int n)
{
// if true, then all bits are set
if (((n + 1) & n) == 0)
return true;
// else all bits are not set
return false;
}
// function to check if a number
// has bits in alternate pattern
static bool bitsAreInAltOrder(int n)
{
int num = n ^ (n >> 1);
// to check if all bits are set
// in 'num'
return allBitsAreSet(num);
}
// Driver Code
public static void Main()
{
int n = 10;
if (bitsAreInAltOrder(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Sam007
PHP
> 1);
// to check if all bits
// are set in 'num'
return allBitsAreSet($num);
}
// Driver Code
$n = 10;
if (bitsAreInAltOrder($n))
echo "Yes";
else
echo "No";
// This code is contributed by aj_36
?>
Yes