Gray Code | Practice | GeeksforGeeks

N = 2
Output: 
00 01 11 10
Explanation: 
00 and 01 differ by one bit.
01 and 11 differ by one bit.
11 and 10 also differ by one bit.
Input:
N=3
Output:
000 001 011 010 110 111 101 100
Explanation:
000 and 001 differ by one bit.
001 and 011 differ by one bit.
011 and 010 differ by one bit.
Similarly, every successive pattern 
differs by one bit.
0
bokonist6 days ago
0.07s C++ code. Better than the bit manipulation solution in the comments (not really sure why this runs faster)
Logic is, at index 0 from end of all strings in the final answer, the pattern repeats: 01 10
for index 1 from end, pattern is 0011 1100
for index 2 from end, pattern is 00001111 11110000
so generate the pattern (p), find the reverse (r) and keep appending p and r to the beginning of each string till you append 1 char to every string in the ans
.
.
vector<string> graycode(int n)
{
    //code here
    string s;
    vector<string> ans;
    for(int i=0;i<pow(2,n);i++)
        ans.push_back("");
    
    string pattern;
    for(int i=0;i<n;i++)
    {
        pattern="";
        for(int k=0;k<pow(2,i);k++)
            pattern+="0";
        for(int k=0;k<pow(2,i);k++)
            pattern+="1";
        int j=0;
        while(j<pow(2,n))
        {
            for(int m=0;m<pattern.size();m++)
            {
                ans[j]= pattern[m]+ans[j];
                j++;
            }
            if(j>=pow(2,n))
                break;
            for(int m=pattern.size()-1;m>=0;m--)
            {
                ans[j]= pattern[m]+ ans[j];
                j++;
            }
        }
        
    }
    return ans;
}
0
wangechiveronica942 months ago
// 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 codesvoid 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];   }
0
prakharsh20002 months ago
C++ Recursive Solution
vector<string> graycode(int n)   {  //base case      if(n==1){        vector<string>s;         s.push_back("0") ; s.push_back("1") ;         return s ;     }     vector<string>v ;     vector<string>t ;      t=graycode(n-1) ;      for(auto x:t){          v.push_back("0"+x) ;      }      for(int i=t.size()-1 ;i>=0 ;i--){          v.push_back("1"+t[i]) ;      }      return v ;       //code here   }
0
rahulgp15513 months ago
// { Driver Code Starts//Initial Template for C++
#include<bits/stdc++.h>using namespace std;
// } Driver Code Ends//User function Template for C++
class Solution{   public:     int b2g(int n)  {            // Your code here      if(n==0)      return 0;      int set = 31;      while((n>>set)==0)      {          set--;      }      int res = 1<<set;            while(set>0)      {          int temp = (n>>set)&1;          set--;          temp = temp^((n>>set)&1);          res = res|(temp<<set);      }      return res;        }  vector<string> graycode(int n)  {      //code here      string ans ="";      for(int i=0;i<n;i++)      {          ans+="0";      }      vector<string> res((1<<n),ans);      for(int i=1;i<(1<<n);i++)      {          int temp = b2g(i);          int shift=0;          while(temp)          {              if(temp&1)              {                  res[i][n-1-shift]='1';              }              shift++;              temp=temp>>1;          }      }            return res;  }};
// { Driver Code Starts.
int main(){   int t;   cin>>t;      while(t--)   {       int n;       cin>>n;              Solution ob;       vector<string> ans= ob.graycode(n);       for(int i=0;i<ans.size();i++)           cout<<ans[i]<<" ";                  cout<<"\n";   }}
 
 // } Driver Code Ends
0
shiva10903 months ago
if(n == 1){           vector<string> v;           v.push_back("0");           v.push_back("1");           return v;       }              vector<string> graySub = graycode(n-1);              vector<string> ans;              for(int i = 0; i < graySub.size(); i++){           ans.push_back("0"+graySub[i]);       }              reverse(graySub.begin(),graySub.end());              for(int i = 0; i < graySub.size(); i++){           ans.push_back("1"+graySub[i]);       }       return ans;
+4
purveshpatil4 months ago
Best Optimal Solution in 0.2 time
XOR the number itself with its 1 right shift to get its gray code
string convertToBinary (int n, int N) {       vi v;       int temp = N;       while(temp) {           v.pb(n & 1);           n >>= 1;           temp >>= 1;       }       string s = "";       for(int i=v.size()-1; i>=0; i--){           s += to_string(v[i]);        }       return s;   }         vector<string> graycode(int n)   {       int N = (1 << (n-1));       vector<string> v;       for(int i=0; i<(N<<1); i++) {           int num1 = (i >> 1);           int res = i ^ num1;           string s = convertToBinary(res, (1 << (n-1)));           v.push_back(s);       }       return v;   }
-1
rahuldubey104 months ago
class Solution{   public:   int b2g(int n)   {              // Your code here       if(n==0)       return 0;       int set = 31;       while((n>>set)==0)       {           set--;       }       int res = 1<<set;              while(set>0)       {           int temp = (n>>set)&1;           set--;           temp = temp^((n>>set)&1);           res = res|(temp<<set);       }       return res;          }   vector<string> graycode(int n)   {       //code here       string ans ="";       for(int i=0;i<n;i++)       {           ans+="0";       }       vector<string> res((1<<n),ans);       for(int i=1;i<(1<<n);i++)       {           int temp = b2g(i);           int shift=0;           while(temp)           {               if(temp&1)               {                   res[i][n-1-shift]='1';               }               shift++;               temp=temp>>1;           }       }              return res;   }};
+1
chessnoobdj4 months ago
EASY C++
vector<string> graycode(int n)
    {
        vector <string> vec;
        int num = pow(2, n);
        for(int i=0; i<num; i++){
            string str = "";
            int gray_num = i^(i>>1);
            str = bitset<16>(gray_num).to_string();
            str = str.substr(16-n, n);
            vec.push_back(str);
        }
        return vec;
    }
vector<string> graycode(int n)
    {
        vector <string> vec;
        for(int i=0; i<pow(2, n); i++)
            vec.push_back((bitset<16>(i^(i>>1)).to_string()).substr(16-n, n));
        return vec;
    }
0
abhay3programmer4 months ago
vector<string> solver(int n){
        if(n == 1){
            vector<string>s;
            s.push_back("0");
            s.push_back("1");
            return s;
        }
        vector<string> vec = solver(n-1);
        vector<string> res;
        for(int i =0;i<vec.size() ;i++){
            res.push_back("0"+vec[i]);
        }
        for(int i =vec.size() - 1;i>=0;i--){
            res.push_back("1"+vec[i]);
        }
        return res;
    }
    vector<string> graycode(int n)
    {
       return solver(n);
    }
0
harishk2711994 months ago
vector<string> v;       if(n==1){           v.push_back("0");           v.push_back("1");           return v;                  }       v = graycode(n-1);       vector<string> s;       int k = v.size();       for(int i =0;i<k;i++){           s.push_back("0"+v[i]);                  }       for(int i =k-1;i>=0;i--){           s.push_back("1"+v[i]);                  }       return s;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.