The realization of gray code

Source: Internet
Author: User

Problem: Gray code refers to a set of number of codes, if any two adjacent code only one binary number is different, this code is called Gray Code, please write a function, using recursive method to generate N-bit gray code.

Given an integer n, return the gray code of N-Bits, in order from 0 onwards.

Test examples:
1
return: ["0", "1"]

For example: when n = 2 o'clock, the gray code is: {00,01,11,10}

When n = 3 o'clock, Gray code is: {000,001,010,011,111,110,101,100}

Remember before the digital logic course should be learned. First known as the size of N, we can know that it corresponds to the number of gray code is 2^n, so the size of the returned array is 2^n. Then, the gray code of n must be related to the Gray Code of n-1. Therefore, we should start from 1, in turn, to know the gray Code of N, which is a recursive topic.

Key to analyze: Known n-1 Gray Code, then N of the Gray Code of the first and length-i-1 bits can be determined, respectively, plus 0 and 1.

Code:

ImportJava.util.*; Public classGraycode { PublicString[] Getgray (intN) {//Write code hereString[] s =NewString[2]; s[0] = "0"; s[1] = "1"; if(n = = 1)            returns; intt = 2;  while(T <=N) {s=Getgraycode (S, t); T++; }        returns; }         PublicString[] Getgraycode (string[] Last,intN) {string[] res=Newstring[(int) Math.pow (2, N)];  for(inti=0; i<last.length; i++) {Res[i]= "0" +Last[i]; Res[res.length-1-i] = "1" +Last[i]; }        returnRes; }}

The realization of gray code

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.