
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Gray Code in C++
As we know that the gray code is a binary numeral system where two successive values differ in only one bit. Suppose we have a non-negative integer n representing the total number of bits in the code. We have to print the sequence of gray code. A gray code sequence must begin with 0. So if the input is 2, then the result will be [0,1,3,2], this is because gray of 0 is 00, gray of 1 is 01, gray of 2 is 11, and gray of 3 is 10.
To solve this, we will follow these steps −
- create one array ans
- find gray code for each number and add them into ans array.
- To convert into gray, we will take the number and perform XOR after shifting the number 1 bit to the right.
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<int> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> grayCode(int n) { vector <int> ans; for(int i =0; i<1<<n; i++){ ans.push_back(i^(i>>1)); } return ans; } }; main(){ Solution ob; print_vector(ob.grayCode(4)); }
Input
4
Output
[0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8, ]
- Related Articles
- What is Gray code?\n
- Conversion of Binary to Gray Code\n
- Conversion of Gray Code to Binary\n
- Binary to Gray code using recursion in C program
- Python Program to Convert Gray Code to Binary
- Python Program to Convert Binary to Gray Code
- Decimal Equivalent of Gray Code and Its Inverse
- Program to convert gray code for a given number in python
- C++ Program to convert the Binary number to Gray code using recursion
- What is Gray Hat Hacking?
- Fighting Gray Hair with Vitamins
- 8085 program to convert gray to binary
- Filter gray image, black around png in Internet Explorer 8
- 8085 program to convert binary numbers to gray
- How to gray out (disable) a Tkinter Frame?

Advertisements