# Gray Code in C++

C++Server Side ProgrammingProgramming

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 −

Live Demo

#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, ]
Published on 31-Jan-2020 06:15:27