the nth gray code

后端 未结 4 1705
眼角桃花
眼角桃花 2020-12-09 13:16

the formula for calculating nth gray code is :

(n-1) XOR (floor((n-1)/2))  
(Source: wikipedia)

I encoded it as:

int gray(         


        
4条回答
  •  清歌不尽
    2020-12-09 14:06

    Prove by induction.

    Hint: The 1<th to (1<<(k+1))-1th values are twice the 1<<(k-1)th to (1<th values, plus either zero or one.

    Edit: That was way too confusing. What I really mean is,

    gray(2*n) and gray(2*n+1) are 2*gray(n) and 2*gray(n)+1 in some order.

提交回复
热议问题