Gray Code Grey

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.