Leetcode first _ Gray Code

Source: Internet
Author: User

Tag: style blog color Io AR for SP Div 2014

When it comes to Gray Code, no one knows how to use it. I am not very clear about it. My roommate should be an expert. The generation rule is not very obvious. As I saw in my post, I cannot find it now ..

This is the idea. If there are N bits and draw a horizontal line below the 2nd ^ (n-1) code, you will find that, except for the first bit, other bits are symmetric about this line, the following example uses a three-digit Gray code:

000

001

011

010

---------------------

110

111

101

100

It's amazing. I used to know this rule. From the beginning of a gray code, 0, 1, start, each symmetric add 0 and 1 in front of the previous one, get all gray codes of the next length.

I did not write this question so much, and I was a little lazy. Due to another more concise method, I have not yet thoroughly understood the detailed principle. Should it be the method used for Gray Code definition? The code is pasted below:

class Solution {public:    vector<int> grayCode(int n) {        vector<int> res;        if(n == 0){            res.push_back(0);        }else{            for(int i=0;i<pow(2, n);i++)                res.push_back((i>>1)^i);        }        return res;    }};


Leetcode first _ 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.