it requires prior knowledge: the graycode can be converted from normal binary for n bits labeled from n-1, n-2, .. 0, here is the formula: GrayBit(i) = NormalBit(i) xor NormalBit(i-1)
| 15 | // for n bits labeled from n-1, n-2, .. 0, here is the formula: |
| 16 | // GrayBit(i) = NormalBit(i) xor NormalBit(i-1) |
| 17 | vector<int> grayCode(int n) { |
| 18 | unsigned long long binary = 0; |
| 19 | int len = pow(2,n); |
| 20 | vector <int > res (len, 0); |
| 21 | for (int i=0; i<len; i ++, binary ++) { |
| 22 | unsigned long long t = 0; |
| 23 | for (int j=0; j<n; j ++) { |
| 24 | int shift = n - j - 1; |
| 25 | t <<= 1; |
| 26 | t ^= ((binary >> shift) & 1) xor ((binary >> (shift + 1)) & 1); |
| 27 | } |
| 28 | res[i] = t; |
| 29 | } |
| 30 | return res; |
| 31 | } |
| 32 | }; |
| 33 | |
| 34 | int main() { |