📜  从K开始生成N位格雷码

📅  最后修改于: 2021-05-25 08:00:46             🧑  作者: Mango

给定值NK ,任务是从值K开始生成N位格雷码。
例子:

方法:

  • 格雷码是其中两个连续数字之间的汉明距离为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


Javascript


输出:
2 3 1 0 4 5 7 6