Easy c++ solution: Successfully submitted


#1

int bin_to_dec(vector v)
{
int sum=0;
for(int i=0;i<v.size();i++)
sum+=(v[i]*pow(2,i));
return sum;
}
vector dec_to_bin(int n, int A)
{
vector v;
while(n>0)
{
v.push_back(n%2);
n/=2;
}
while(v.size()<A-1) //to fill all A-1 digits, also I have returned reverse binary representation
v.push_back(0); //have converted binary to decimal accordingly
return v;
}
vector Solution::grayCode(int A)
{
if(A==1)
{
vector v;
v.push_back(0);
v.push_back(1);
return v;
}
int i;
vector v2;
vector v1;
v1=Solution::grayCode(A-1);
vector<vector> v;
for(i=0;i<v1.size();i++)
{
v2=dec_to_bin(v1[i],A);
v.push_back(v2);
}
for(i=v.size()-1;i>=0;i–)
v.push_back(v[i]);
for(i=0;i<v.size()/2;i++)
v[i].push_back(0);
for(i=v.size()/2;i<v.size();i++)
v[i].push_back(1);
v1.clear();
for(i=0;i<v.size();i++)
{
int x=bin_to_dec(v[i]);
v1.push_back(x);
}
return v1;
}