给定值N和K ,任务是从值K开始生成N位格雷码。
例子:
Input: N = 2, K = 3
Output: 3 2 0 1
Explanation:
3 -> 11
2 -> 10
0 -> 00
1 -> 01
Each value differ by only one bit from the next value in their binary representation.
Input: N = 3, K = 2
Output: 2 3 1 0 4 5 7 6
方法:
- 格雷码是其中两个连续数字之间的汉明距离为1的数字。
- 与N位格雷码的每个元素的XOR生成的汉明距离序列为1。
- 由于N位格雷码的第一个元素是K,因此可以通过对0进行XOR来获得,即(K ^ 0)=K。
- 因此,序列将从0开始,每个连续元素的二进制表示形式仅相差一位。
下面是上述方法的实现:
C++
// C++ program Generating N-bit
// Gray Code starting from K
#include
using namespace std;
// Function to Generating N-bit
// Gray Code starting from K
void genSequence(int n, int val)
{
for (int i = 0; i < (1 << n); i++) {
// Generate gray code of corresponding
// binary number of integer i.
int x = i ^ (i >> 1) ^ val;
cout << x << " ";
}
}
// Driver code
int main()
{
int n = 3, k = 2;
genSequence(n, k);
return 0;
}
Java
// Java program Generating N-bit
// Gray Code starting from K
class GFG {
// Function to Generating N-bit
// Gray Code starting from K
static void genSequence(int n, int val)
{
for (int i = 0; i < (1 << n); i++) {
// Generate gray code of corresponding
// binary number of integer i.
int x = i ^ (i >> 1) ^ val;
System.out.print(x + " ");
}
}
// Driver code
public static void main (String[] args)
{
int n = 3, k = 2;
genSequence(n, k);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 program Generating N-bit
# Gray Code starting from K
# Function to Generating N-bit
# Gray Code starting from K
def genSequence(n, val) :
for i in range(1 << n) :
# Generate gray code of corresponding
# binary number of integer i.
x = i ^ (i >> 1) ^ val;
print(x, end= " ");
# Driver code
if __name__ == "__main__" :
n = 3; k = 2;
genSequence(n, k);
# This code is contributed by AnkitRai01
C#
// C# program Generating N-bit
// Gray Code starting from K
using System;
class GFG
{
// Function to Generating N-bit
// Gray Code starting from K
static void genSequence(int n, int val)
{
for (int i = 0; i < (1 << n); i++)
{
// Generate gray code of corresponding
// binary number of integer i.
int x = i ^ (i >> 1) ^ val;
Console.Write(x + " ");
}
}
// Driver code
public static void Main()
{
int n = 3, k = 2;
genSequence(n, k);
}
}
// This code is contributed by AnkitRai01
输出:
2 3 1 0 4 5 7 6