Generate n-bit Gray Codes
Last Updated :
03 Feb, 2023
Given a number N, generate bit patterns from 0 to 2^N-1 such that successive patterns differ by one bit.
Examples:
Input: N = 2
Output: 00 01 11 10
Input: N = 3
Output: 000 001 011 010 110 111 101 100
Method-1
The above sequences are Gray Codes of different widths. Following is an interesting pattern in Gray Codes.
n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using following steps.
- Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.
- Modify the list L1 by prefixing a '0' in all codes of L1.
- Modify the list L2 by prefixing a '1' in all codes of L2.
- Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes
For example, following are steps for generating the 3-bit Gray code list from the list of 2-bit Gray code list. L1 = {00, 01, 11, 10} (List of 2-bit Gray Codes) L2 = {10, 11, 01, 00} (Reverse of L1) Prefix all entries of L1 with '0', L1 becomes {000, 001, 011, 010} Prefix all entries of L2 with '1', L2 becomes {110, 111, 101, 100} Concatenate L1 and L2, we get {000, 001, 011, 010, 110, 111, 101, 100} To generate n-bit Gray codes, we start from list of 1 bit Gray codes. The list of 1 bit Gray code is {0, 1}. We repeat above steps to generate 2 bit Gray codes from 1 bit Gray codes, then 3-bit Gray codes from 2-bit Gray codes till the number of bits becomes equal to n.
Below is the implementation of the above approach:
C++
// C++ program to generate n-bit Gray codes
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// This function generates all n bit Gray codes and prints the
// generated codes
void generateGrayarr(int n)
{
// base case
if (n <= 0)
return;
// 'arr' will store all generated codes
vector<string> arr;
// start with one-bit pattern
arr.push_back("0");
arr.push_back("1");
// Every iteration of this loop generates 2*i codes from previously
// generated i codes.
int i, j;
for (i = 2; i < (1<<n); i = i<<1)
{
// Enter the previously generated codes again in arr[] in reverse
// order. Nor arr[] has double number of codes.
for (j = i-1 ; j >= 0 ; j--)
arr.push_back(arr[j]);
// append 0 to the first half
for (j = 0 ; j < i ; j++)
arr[j] = "0" + arr[j];
// append 1 to the second half
for (j = i ; j < 2*i ; j++)
arr[j] = "1" + arr[j];
}
// print contents of arr[]
for (i = 0 ; i < arr.size() ; i++ )
cout << arr[i] << endl;
}
// Driver program to test above function
int main()
{
generateGrayarr(3);
return 0;
}
Java
// Java program to generate n-bit Gray codes
import java.util.*;
class GfG {
// This function generates all n bit Gray codes and prints the
// generated codes
static void generateGrayarr(int n)
{
// base case
if (n <= 0)
return;
// 'arr' will store all generated codes
ArrayList<String> arr = new ArrayList<String> ();
// start with one-bit pattern
arr.add("0");
arr.add("1");
// Every iteration of this loop generates 2*i codes from previously
// generated i codes.
int i, j;
for (i = 2; i < (1<<n); i = i<<1)
{
// Enter the previously generated codes again in arr[] in reverse
// order. Nor arr[] has double number of codes.
for (j = i-1 ; j >= 0 ; j--)
arr.add(arr.get(j));
// append 0 to the first half
for (j = 0 ; j < i ; j++)
arr.set(j, "0" + arr.get(j));
// append 1 to the second half
for (j = i ; j < 2*i ; j++)
arr.set(j, "1" + arr.get(j));
}
// print contents of arr[]
for (i = 0 ; i < arr.size() ; i++ )
System.out.println(arr.get(i));
}
// Driver program to test above function
public static void main(String[] args)
{
generateGrayarr(3);
}
}
Python3
# Python3 program to generate n-bit Gray codes
import math as mt
# This function generates all n bit Gray
# codes and prints the generated codes
def generateGrayarr(n):
# base case
if (n <= 0):
return
# 'arr' will store all generated codes
arr = list()
# start with one-bit pattern
arr.append("0")
arr.append("1")
# Every iteration of this loop generates
# 2*i codes from previously generated i codes.
i = 2
j = 0
while(True):
if i >= 1 << n:
break
# Enter the previously generated codes
# again in arr[] in reverse order.
# Nor arr[] has double number of codes.
for j in range(i - 1, -1, -1):
arr.append(arr[j])
# append 0 to the first half
for j in range(i):
arr[j] = "0" + arr[j]
# append 1 to the second half
for j in range(i, 2 * i):
arr[j] = "1" + arr[j]
i = i << 1
# print contents of arr[]
for i in range(len(arr)):
print(arr[i])
# Driver Code
generateGrayarr(3)
# This code is contributed
# by Mohit kumar 29
C#
using System;
using System.Collections.Generic;
// C# program to generate n-bit Gray codes
public class GfG
{
// This function generates all n bit Gray codes and prints the
// generated codes
public static void generateGrayarr(int n)
{
// base case
if (n <= 0)
{
return;
}
// 'arr' will store all generated codes
List<string> arr = new List<string> ();
// start with one-bit pattern
arr.Add("0");
arr.Add("1");
// Every iteration of this loop generates 2*i codes from previously
// generated i codes.
int i, j;
for (i = 2; i < (1 << n); i = i << 1)
{
// Enter the previously generated codes again in arr[] in reverse
// order. Nor arr[] has double number of codes.
for (j = i - 1 ; j >= 0 ; j--)
{
arr.Add(arr[j]);
}
// append 0 to the first half
for (j = 0 ; j < i ; j++)
{
arr[j] = "0" + arr[j];
}
// append 1 to the second half
for (j = i ; j < 2 * i ; j++)
{
arr[j] = "1" + arr[j];
}
}
// print contents of arr[]
for (i = 0 ; i < arr.Count ; i++)
{
Console.WriteLine(arr[i]);
}
}
// Driver program to test above function
public static void Main(string[] args)
{
generateGrayarr(3);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Javascript program to generate n-bit Gray codes
// This function generates all n bit Gray codes and prints the
// generated codes
function generateGrayarr(n)
{
// base case
if (n <= 0)
return;
// 'arr' will store all generated codes
let arr = [];
// start with one-bit pattern
arr.push("0");
arr.push("1");
// Every iteration of this loop generates 2*i codes from previously
// generated i codes.
let i, j;
for (i = 2; i < (1<<n); i = i<<1)
{
// Enter the previously generated codes again in arr[] in reverse
// order. Nor arr[] has double number of codes.
for (j = i-1 ; j >= 0 ; j--)
arr.push(arr[j]);
// append 0 to the first half
for (j = 0 ; j < i ; j++)
arr[j]= "0" + arr[j];
// append 1 to the second half
for (j = i ; j < 2*i ; j++)
arr[j]= "1" + arr[j];
}
// print contents of arr[]
for (i = 0 ; i < arr.length ; i++ )
document.write(arr[i]+"<br>");
}
// Driver program to test above function
generateGrayarr(3);
// This code is contributed by unknown2108
</script>
Output000
001
011
010
110
111
101
100
Time Complexity: O(2N)
Auxiliary Space: O(2N)
Method 2: Recursive Approach
The idea is to recursively append the bit 0 and 1 each time until the number of bits is not equal to N.
Base Condition: The base case for this problem will be when the value of N = 0 or 1.
If (N == 0)
return {"0"}
if (N == 1)
return {"0", "1"}
Recursive Condition: Otherwise, for any value greater than 1, recursively generate the gray codes of the N - 1 bits and then for each of the gray code generated add the prefix 0 and 1.
Below is the implementation of the above approach:
C++
// C++ program to generate
// n-bit Gray codes
#include <bits/stdc++.h>
using namespace std;
// This function generates all n
// bit Gray codes and prints the
// generated codes
vector<string> generateGray(int n)
{
// Base case
if (n <= 0)
return {"0"};
if (n == 1)
{
return {"0","1"};
}
//Recursive case
vector<string> recAns=
generateGray(n-1);
vector<string> mainAns;
// Append 0 to the first half
for(int i=0;i<recAns.size();i++)
{
string s=recAns[i];
mainAns.push_back("0"+s);
}
// Append 1 to the second half
for(int i=recAns.size()-1;i>=0;i--)
{
string s=recAns[i];
mainAns.push_back("1"+s);
}
return mainAns;
}
// Function to generate the
// Gray code of N bits
void generateGrayarr(int n)
{
vector<string> arr;
arr=generateGray(n);
// print contents of arr
for (int i = 0 ; i < arr.size();
i++ )
cout << arr[i] << endl;
}
// Driver Code
int main()
{
generateGrayarr(3);
return 0;
}
Java
// Java program to generate
// n-bit Gray codes
import java.io.*;
import java.util.*;
class GFG
{
// This function generates all n
// bit Gray codes and prints the
// generated codes
static ArrayList<String> generateGray(int n)
{
// Base case
if (n <= 0)
{
ArrayList<String> temp =
new ArrayList<String>(){{add("0");}};
return temp;
}
if(n == 1)
{
ArrayList<String> temp =
new ArrayList<String>(){{add("0");add("1");}};
return temp;
}
// Recursive case
ArrayList<String> recAns = generateGray(n - 1);
ArrayList<String> mainAns = new ArrayList<String>();
// Append 0 to the first half
for(int i = 0; i < recAns.size(); i++)
{
String s = recAns.get(i);
mainAns.add("0" + s);
}
// Append 1 to the second half
for(int i = recAns.size() - 1; i >= 0; i--)
{
String s = recAns.get(i);
mainAns.add("1" + s);
}
return mainAns;
}
// Function to generate the
// Gray code of N bits
static void generateGrayarr(int n)
{
ArrayList<String> arr = new ArrayList<String>();
arr = generateGray(n);
// print contents of arr
for (int i = 0 ; i < arr.size(); i++)
{
System.out.println(arr.get(i));
}
}
// Driver Code
public static void main (String[] args)
{
generateGrayarr(3);
}
}
// This code is contributed by rag2127.
Python3
# Python3 program to generate
# n-bit Gray codes
# This function generates all n
# bit Gray codes and prints the
# generated codes
def generateGray(n):
# Base case
if (n <= 0):
return ["0"]
if (n == 1):
return [ "0", "1" ]
# Recursive case
recAns = generateGray(n - 1)
mainAns = []
# Append 0 to the first half
for i in range(len(recAns)):
s = recAns[i]
mainAns.append("0" + s)
# Append 1 to the second half
for i in range(len(recAns) - 1, -1, -1):
s = recAns[i]
mainAns.append("1" + s)
return mainAns
# Function to generate the
# Gray code of N bits
def generateGrayarr(n):
arr = generateGray(n)
# Print contents of arr
print(*arr, sep = "\n")
# Driver Code
generateGrayarr(3)
# This code is contributed by avanitrachhadiya2155
C#
// Java program to generate
// n-bit Gray codes
using System;
using System.Collections.Generic;
class GFG {
// This function generates all n
// bit Gray codes and prints the
// generated codes
static List<String> generateGray(int n)
{
// Base case
if (n <= 0) {
List<String> temp = new List<String>();
temp.Add("0");
return temp;
}
if (n == 1) {
List<String> temp = new List<String>();
temp.Add("0");
temp.Add("1");
return temp;
}
// Recursive case
List<String> recAns = generateGray(n - 1);
List<String> mainAns = new List<String>();
// Append 0 to the first half
for (int i = 0; i < recAns.Count; i++) {
String s = recAns[i];
mainAns.Add("0" + s);
}
// Append 1 to the second half
for (int i = recAns.Count - 1; i >= 0; i--) {
String s = recAns[i];
mainAns.Add("1" + s);
}
return mainAns;
}
// Function to generate the
// Gray code of N bits
static void generateGrayarr(int n)
{
List<String> arr = new List<String>();
arr = generateGray(n);
// print contents of arr
for (int i = 0; i < arr.Count; i++)
{
Console.WriteLine(arr[i]);
}
}
// Driver Code
public static void Main(String[] args)
{
generateGrayarr(3);
}
}
// This code is contributed by grand_master.
JavaScript
<script>
// Javascript program to generate
// n-bit Gray codes
// This function generates all n
// bit Gray codes and prints the
// generated codes
function generateGray(n)
{
// Base case
if (n <= 0)
{
let temp =["0"];
return temp;
}
if(n == 1)
{
let temp =["0","1"];
return temp;
}
// Recursive case
let recAns = generateGray(n - 1);
let mainAns = [];
// Append 0 to the first half
for(let i = 0; i < recAns.length; i++)
{
let s = recAns[i];
mainAns.push("0" + s);
}
// Append 1 to the second half
for(let i = recAns.length - 1; i >= 0; i--)
{
let s = recAns[i];
mainAns.push("1" + s);
}
return mainAns;
}
// Function to generate the
// Gray code of N bits
function generateGrayarr(n)
{
let arr = [];
arr = generateGray(n);
// print contents of arr
for (let i = 0 ; i < arr.length; i++)
{
document.write(arr[i]+"<br>");
}
}
// Driver Code
generateGrayarr(3);
// This code is contributed by ab2127
</script>
Output000
001
011
010
110
111
101
100
Time Complexity: O(2N)
Auxiliary Space: O(2N)
Method3: (Using bitset)
We should first find binary no from 1 to n and then convert it into string and then print it using substring function of string.
Below is the implementation of the above idea:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
void GreyCode(int n)
{
// power of 2
for (int i = 0; i < (1 << n); i++)
{
// Generating the decimal
// values of gray code then using
// bitset to convert them to binary form
int val = (i ^ (i >> 1));
// Using bitset
bitset<32> r(val);
// Converting to string
string s = r.to_string();
cout << s.substr(32 - n) << " ";
}
}
// Driver Code
int main()
{
int n;
n = 4;
// Function call
GreyCode(n);
return 0;
}
Java
// Java implementation of the above approach
import java.lang.Math;
class GFG {
static void GreyCode(int n)
{
// power of 2
for (int i = 0; i < (1 << n); i++)
{
// Generating the decimal
// values of gray code then using
// bitset to convert them to binary form
int val = (i ^ (i >> 1));
// Converting to binary string
String s = Integer.toBinaryString(val);
System.out.print(
String.format("%1$" + n + "s", s)
.replace(' ', '0')
+ " ");
}
}
// Driver Code
public static void main(String[] args)
{
int n = 4;
// Function call
GreyCode(n);
}
}
// This code is contributed by phasing17
Python3
# Python3 implementation of the above approach
def GreyCode(n):
# power of 2
for i in range(1 << n):
# Generating the decimal
# values of gray code then using
# bitset to convert them to binary form
val = (i ^ (i >> 1))
# Converting to binary string
s = bin(val)[2::]
print(s.zfill(n), end = " ")
# Driver Code
n = 4
# Function call
GreyCode(n)
# This code is contributed by phasing17
JavaScript
// JavaScript implementation of the above approach
function GreyCode(n)
{
// power of 2
for (var i = 0; i < (1 << n); i++)
{
// Generating the decimal
// values of gray code then using
// bitset to convert them to binary form
var val = (i ^ (i >> 1));
// Converting to binary string
s = val.toString(2);
process.stdout.write(s.padStart(4, '0') + " ");
}
}
// Driver Code
let n = 4;
// Function call
GreyCode(n);
// This code is contributed by phasing17
C#
// C# implementation of the above approach
using System;
class GFG {
static void GreyCode(int n)
{
// power of 2
for (int i = 0; i < (1 << n); i++) {
// Generating the decimal
// values of gray code then using
// bitset to convert them to binary form
int val = (i ^ (i >> 1));
// Converting to binary string
string s = Convert.ToString(val, 2);
Console.Write(s.PadLeft(4, '0') + " ");
}
}
// Driver Code
public static void Main(string[] args)
{
int n = 4;
// Function call
GreyCode(n);
}
}
// This code is contributed by phasing17
Output0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000
Time Complexity: O(2N)
Auxiliary Space: O(N)
Similar Reads
Bitwise Algorithms
Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Introduction to Bitwise Algorithms - Data Structures and Algorithms Tutorial
Bit stands for binary digit. A bit is the basic unit of information and can only have one of two possible values that is 0 or 1. In our world, we usually with numbers using the decimal base. In other words. we use the digit 0 to 9 However, there are other number representations that can be quite use
15+ min read
Bitwise Operators in C
In C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Bitwise Operators in Java
In Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming.There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level. T
6 min read
Python Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format.Note: Python bitwis
5 min read
JavaScript Bitwise Operators
In JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
All about Bit Manipulation
Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementa
14 min read
What is Endianness? Big-Endian & Little-Endian
Computers operate using binary code, a language made up of 0s and 1s. This binary code forms the foundation of all computer operations, enabling everything from rendering videos to processing complex algorithms. A single bit is a 0 or a 1, and eight bits make up a byte. While some data, such as cert
5 min read
Bits manipulation (Important tactics)
Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming Table of Contents Compute XOR from 1 to n (direct method)Count of numbers (x) smaller than or equal to n such that n+x = n^xHow to know if a number is a power of 2?Find XOR of all
15+ min read
Easy Problems on Bit Manipulations and Bitwise Algorithms
Binary representation of a given number
Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length.Examples: Input: n = 2Output: 00000000000000000000000000000010Input: n = 0Output: 000000000000
6 min read
Count set bits in an integer
Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bitsInput : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits[Naive Approach] - One by One CountingTh
15+ min read
Add two bit strings
Given two binary strings s1 and s2 consisting of only 0s and 1s. Find the resultant string after adding the two Binary Strings.Note: The input strings may contain leading zeros but the output string should not have any leading zeros.Examples:Input: s1 = "1101", s2 = "111"Output: 10100Explanation: "1
1 min read
Turn off the rightmost set bit
Given an integer n, turn remove turn off the rightmost set bit in it. Input: 12Output: 8Explanation : Binary representation of 12 is 00...01100. If we turn of the rightmost set bit, we get 00...01000 which is binary representation of 8Input: 7 Output: 6 Explanation : Binary representation for 7 is 0
7 min read
Rotate bits of a number
Given a 32-bit integer n and an integer d, rotate the binary representation of n by d positions in both left and right directions. After each rotation, convert the result back to its decimal representation and return both values in an array as [left rotation, right rotation].Note: A rotation (or cir
7 min read
Compute modulus division by a power-of-2-number
Given two numbers n and d where d is a power of 2 number, the task is to perform n modulo d without the division and modulo operators.Input: 6 4Output: 2 Explanation: As 6%4 = 2Input: 12 8Output: 4Explanation: As 12%8 = 4Input: 10 2Output: 0Explanation: As 10%2 = 0Approach:The idea is to leverage bi
3 min read
Find the Number Occurring Odd Number of Times
Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space. Examples : Input : arr = {1, 2, 3, 2, 3, 1, 3}Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5}Output : 5 Recommended
12 min read
Program to find whether a given number is power of 2
Given a positive integer n, the task is to find if it is a power of 2 or not.Examples: Input : n = 16Output : YesExplanation: 24 = 16Input : n = 42Output : NoExplanation: 42 is not a power of 2Input : n = 1Output : YesExplanation: 20 = 1Approach 1: Using Log - O(1) time and O(1) spaceThe idea is to
12 min read
Find position of the only set bit
Given a number n containing only 1 set bit in its binary representation, the task is to find the position of the only set bit. If there are 0 or more than 1 set bits, then return -1. Note: Position of set bit '1' should be counted starting with 1 from the LSB side in the binary representation of the
8 min read
Check for Integer Overflow
Given two integers a and b. The task is to design a function that adds two integers and detects overflow during the addition. If the sum does not cause an overflow, return their sum. Otherwise, return -1 to indicate an overflow.Note: You cannot use type casting to a larger data type to check for ove
7 min read
Find XOR of two number without using XOR operator
Given two integers, the task is to find XOR of them without using the XOR operator.Examples : Input: x = 1, y = 2Output: 3Input: x = 3, y = 5Output: 6Approach - Checking each bit - O(log n) time and O(1) spaceA Simple Solution is to traverse all bits one by one. For every pair of bits, check if both
8 min read
Check if two numbers are equal without using arithmetic and comparison operators
Given two numbers, the task is to check if two numbers are equal without using Arithmetic and Comparison Operators or String functions. Method 1 : The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are the same, otherwise non-zero. C++ // C++ program to check if two numbers // a
8 min read
Detect if two integers have opposite signs
Given two integers a and b, the task is to determine whether they have opposite signs. Return true if the signs of the two numbers are different and false otherwise.Examples:Input: a = -5, b = 10Output: trueExplanation: One number is negative and the other is positive, so their signs are different.I
9 min read
Swap Two Numbers Without Using Third Variable
Given two variables a and y, swap two variables without using a third variable. Examples: Input: a = 2, b = 3Output: a = 3, b = 2Input: a = 20, b = 0Output: a = 0, b = 20Input: a = 10, b = 10Output: a = 10, b = 10Table of ContentUsing Arithmetic OperatorsUsing Bitwise XORBuilt-in SwapUsing Arithmeti
6 min read
Russian Peasant (Multiply two numbers using bitwise operators)
Given two integers a and b, the task is to multiply them without using the multiplication operator. Instead of that, use the Russian Peasant Algorithm.Examples:Input: a = 2, b = 5Output: 10Explanation: Product of 2 and 5 is 10.Input: a = 6, b = 9Output: 54Explanation: Product of 6 and 9 is 54.Input:
4 min read