给定一个整数n> 0,任务是确定该整数的位表示形式是否具有备用模式。例如-5具有替代图案,即101。
如果有其他图案,则打印“是”,否则为“否”。在这里,替代模式可以像0101或1010。
例子:
Input : 15
Output : No
Explanation: Binary representation of 15 is 1111.
Input : 10
Output : Yes
Explanation: Binary representation of 10 is 1010.
一种简单的方法是找到其二进制等效项,然后检查其位。
C++
// C++ program to find if a number has alternate
// bit pattern
#include
using namespace std;
// Returns true if n has alternate bit pattern
// else false
bool findPattern(int n)
{
// Store last bit
int prev = n % 2;
n = n/2;
// Traverse through remaining bits
while (n > 0)
{
int curr = n % 2;
// If current bit is same as previous
if (curr == prev)
return false;
prev = curr;
n = n / 2;
}
return true;
}
// Driver code
int main()
{
int n = 10;
if (findPattern(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program to find if a number has alternate
// bit pattern
class Test
{
// Returns true if n has alternate bit pattern
// else false
static boolean findPattern(int n)
{
// Store last bit
int prev = n % 2;
n = n/2;
// Traverse through remaining bits
while (n > 0)
{
int curr = n % 2;
// If current bit is same as previous
if (curr == prev)
return false;
prev = curr;
n = n / 2;
}
return true;
}
// Driver method
public static void main(String args[])
{
int n = 10;
System.out.println(findPattern(n) ? "Yes" : "No");
}
}
Python3
# Python3 program to find if a number
# has alternate bit pattern
# Returns true if n has alternate
# bit pattern else false
def findPattern(n):
# Store last bit
prev = n % 2
n = n // 2
# Traverse through remaining bits
while (n > 0):
curr = n % 2
# If current bit is same as previous
if (curr == prev):
return False
prev = curr
n = n // 2
return True
# Driver code
n = 10
print("Yes") if(findPattern(n)) else print("No")
# This code is contributed by Anant Agarwal.
C#
// Program to find if a number
// has alternate bit pattern
using System;
class Test {
// Returns true if n has alternate
// bit pattern else returns false
static bool findPattern(int n)
{
// Store last bit
int prev = n % 2;
n = n / 2;
// Traverse through remaining bits
while (n > 0) {
int curr = n % 2;
// If current bit is same as previous
if (curr == prev)
return false;
prev = curr;
n = n / 2;
}
return true;
}
// Driver method
public static void Main()
{
int n = 10;
Console.WriteLine(findPattern(n) ? "Yes" : "No");
}
}
// This code is contributed by Anant Agarwal.
PHP
0)
{
$curr = $n % 2;
// If current bit is
// same as previous
if ($curr == $prev)
return false;
$prev = $curr;
$n = floor($n / 2);
}
return true;
}
// Driver code
$n = 10;
if (findPattern($n))
echo "Yes";
else
echo "No";
return 0;
// This code is contributed by nitin mittal.
?>
输出:
Yes
参考:
http://stackoverflow.com/questions/38690278/program-to-check-whether-the-given-integer-has-an-alternate-pattern