Skip to content

Instantly share code, notes, and snippets.

@1604078-MEHEDI
Created June 15, 2019 15:02
Show Gist options
  • Save 1604078-MEHEDI/ae0ce1e5ddc9104164d6ff7eccd5d248 to your computer and use it in GitHub Desktop.
Save 1604078-MEHEDI/ae0ce1e5ddc9104164d6ff7eccd5d248 to your computer and use it in GitHub Desktop.
#include<bits/stdc++.h>
using namespace std;
// this code return nth gray code
//https://leetcode.com/problems/gray-code/
vector<int> grayCode (int n)
{
int lmt = 1 << n;
cout << lmt << endl;
vector<int> ans;
for(int i = 0; i < lmt; i++){
int x = i;
ans.push_back(x ^ (x >> 1));
}
return ans;
}
int rev_grayCode(int g)
{
int n = 0;
for(; g; g >>= 1)
n ^= g;
return n;
}
///https://www.geeksforgeeks.org/gray-to-binary-and-binary-to-gray-conversion/
char xor_c(char a, char b) {return (a == b) ? '0' : '1';}
char flip(char c) {return (c == '0') ? '1' : '0' ;}
// convert binary to Gray
string BtoG(string binary)
{
string gray = "";
gray += binary[0]; // MSB same
for(int i = 1; i < binary.size(); i++)
gray += xor_c(binary[i - 1], binary[i]);
return gray;
}
string GotB(string gray)
{
string binary = "";
binary += gray[0];
for(int i = 1; i < gray.size(); i++){
if(gray[i] == '0') binary += binary[i - 1];
else binary += flip(binary[i - 1]);
}
return binary;
}
int main()
{
/*
int n;
cin >> n;
// auto v = grayCode(n);
cout << rev_grayCode(n)<<endl;
// for(auto x: v)cout << x << " ";
return 0;
//*/
/**
int T;
cin >> T;
while(T--){
string s;
cin >> s;
cout << BtoG(s)<<endl;
}
return 0;
**/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment