CSES Solutions
#2205Introductory Problems

Gray Code

View on CSES

Solution

2205-Gray_Code.cpp
1#include<bits/stdc++.h>
2using namespace std;
3#define int long long
4signed main(){
5  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
6  int n; cin>>n;
7  vector<string> v;
8  v.emplace_back("0"); v.emplace_back("1");
9  for(int i=2;i<1<<n;i<<=1){
10    for(int j=i-1;j>=0;--j) v.emplace_back(v[j]);
11    for(int j=0;j<i;++j) v[j]="0"+v[j];
12    for(int j=i;j<2*i;++j) v[j]="1"+v[j];
13  }
14  for(auto&s:v)cout<<s<<'\n';
15  return 0;
16}

Editorial not yet generated for this problem. Run the editorial generation script to add hints and detailed explanations.