I was reading about gray codes. There I found this algorithm.
int g (int n)
{
return n ^ (n >> 1);
}
Given a number $n$, this finds the $n$th gray code.
Suppose if $n=10$, the answer would be $1111$. Since $n=10(1010)$, $$\begin{align} n>>1 &= 0101 \\ n \wedge (n>>1) &= 1111. \end{align}$$
I can understand the working. But I don't really understand how they derived this? I mean can somebody give me the intuition behind this?
yes you are right answer is $15=1111$
the main point is that ^ mark is xor,which means that Exclusive disjunction or exclusive oris a logical operation that outputs true whenever both inputs differ (one is true, the other is false)
there is time table for it
now >> symbol means simple divide by $2$,in your case $10/2=5$ or $0101$
now we have
$1010$ xor $(0101)$=$1111$
for generally let us find grey codes from 0 to n
answer http://codepad.org/xAMnNA0r
Actually ^ mark shows true at this places where this two sequence differ from each other,which of course is basic idea behind of grey code additional information you can check there
http://mathworld.wolfram.com/GrayCode.html
look also there please
http://www.most.gov.mm/techuni/media/BinaryToGrayCodeConverter.pdf