Java for Leetcode 089 Gray Code

Source: Internet
Author: User

The gray code is a binary numeral system where the successive values are differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code . A Gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2] . Its gray code sequence is:

00-001-111-310-2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, was [0,2,3,1] also a valid gray code sequence according to the above definition.

For now, the judge are able to judge based on one instance of gray code sequence. Sorry about that.

Problem Solving Ideas:

Gray code, learn the principle of communication children's shoes should not be unfamiliar, but gray code generation method is not as described in the topic, the following popular science under the Gray Code generation method:

N=1 Get 0 1

n=2 get 00 01 11 10 (note, 11 and 10 except for the sign bit, and 00 01 symmetrical)

N=3 Get 000 001 011 010 110 111 101 100 (back four bits in addition to the sign bit, and the first four bits symmetrical)

N=4 in turn

Knowing the build process of gray code, the Java implementation is as follows:

   static public list<integer> Graycode (int n) {        list<integer> list=new arraylist<integer> ();        for (int i=0;i<math.pow (2, n); i++) {        int result=0,num=i,temp=n;        while (temp>1) {        if (Num>=math.pow (2, temp-1)) {        num= (int) (2*MATH.POW (2, temp-1)-num-1);        Result+=math.pow (2, temp-1);        }        temp--;        }        Result+=num;        List.add (result);        }        return list;    }

At the same time, the subject has a very concise wording, as follows:

    Public list<integer> Graycode (int n) {        list<integer> res = new arraylist<integer> ();        for (int i = 0; i < (1<<n); ++i)            Res.add (i ^ (i>>1));        return res;    }

Java for Leetcode 089 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.