Gray Code Grey
Gray code Definition: In a set of number of codes, if any two adjacent code only one binary number is different, it is said that this code is gray code (gray code)
Gray code Solution: The last solution to the grey code, in order to each of the prefix 0, get the first half, and then, the gray code reverse, to each prefix 1 is the answer.
For example:
n = 1
gray:0 1
n = 2
00 01 (Order 0 1)
11 10 (reverse 1 0)
Specific code
#include <bits/stdc++.h>using namespace std;//Gray (n) = prefix 0 + order Gray (n-1) prefix 1 + reverse gray (n-1) void Getgraycode (in T arr[], int n) { if (n==1) { arr[1] = 0; ARR[2] = 1; return; } Get n-1 Gray code getgraycode (arr, n-1); int k = 1<< (n-1); for (int i=k; i>0; i--) { //Counter-attack plus prefix arr[2*k+1-i] = arr[i]+k; }} void Printgraycode (int arr[], const int n) {for (int i=1; i<= (1<<n); ++i) { //printf ("%d\n", arr [i]); Bitset<4> bit (arr[i]); cout<<bit<< ""; if (i== (1<< (n-1))) //half time line wrap cout<<endl; } printf ("\ n");} int main (void) { int n = 4; int *code = new int[1<<10]; Getgraycode (code, n); Printgraycode (code, n); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Http://blog.csdn.net/core__code
Gray Code Grey