1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

/*
** The BinaryToGray method is base on the bit of gray cod looply occur: 0,1,1,0
** Hence, we could calcule each bits of gray code by mod 4 to find the matching value
**
** However, after search on the website, the convert formula is just simply as (i>>1) ^ i.
** The ith bit is equal to ith bit plus (i+1)th bit with no carry.
*/
int BinaryToGray(int binary) { int gray = 0; int bit = 0; int convert[4] = {0,1,1,0}; while(binary) { int value = convert[binary%4]; gray |= value << bit; ++ bit; binary >>= 1; } } vector<int> GrayCode(int n) { vector<int> codes; for(int i=0; i< (1<<n); ++i) codes.push_back((i>>1) ^ i); //codes.push_back(BinaryToGray(i)); return codes; }
View Program Text


Test Status