2 lines solution c++


#1

vector Solution::grayCode(int A) {
vector ans;
long long x = pow(2 , A) , i;
for(i=0 ; i < x ; i++)
{
int j = i/2;
ans.push_back(i^j);
}
return ans;
}


#2

nice way
the values of Xor of i and j really give the gray code
can you please elaborate why the xor of these two value lead to gray code in a systematic circular manner if the start is 0


#3

The person is calculating the Gray code equivalent of decimal number.
Given decimal number n with bits positions I (I+1) (I+2) … numbered from left to right
Its Gray code is I (I^(I+1)) ((I+1)^(I+2)) …
Notice each bit is xoring with previous bit
(so if we take a number and right shift it we will bring previous bit position for given bit in current number)
Gray code equivalent hence is for n = n^(n/2)


#4

Really good solution and a nice explanation.