[Leetcode] Gray Code

Source: Internet
Author: User

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

Given a non-negative integerNRepresenting the total number of BITs in the code, print the sequence of Gray code. A gray code sequence must begin with 0.

For example, givenN= 2, return[0, 1, 3, 2]. Its Gray code sequence is:

00 - 001 - 111 - 310 - 2

Note:
For a givenN, A gray code sequence is not uniquely defined.

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

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

 

Idea: Gray code problem.

Binary to Gray code: the highest bit of the binary as the highest bit of gray code. The rest of the gray code are the opposite or of the corresponding binary BITs, which are relatively high.

That is, gray_code (t) = binary_code (t) // T is the highest bit

Gray_code (I) = binary_code (I) ^ binary_code (I + 1) // 0 <= I <t;

 1 class Solution { 2 public: 3     vector<int> grayCode(int n) { 4         vector<int> res; 5         const int size = 1 << n; 6         for (int i = 0; i < size; ++i) { 7             res.push_back((i>>1) ^ i); 8         } 9         10         return res;11         12     }13 };

 

Expansion:

    1. Gray code to binary: the highest bit of binary is Gray code. The binary high level is the same as the gray code high level.

Binary_code (t) = gray_code (t) // T is the highest bit

Binary_code (I) = gray_code (I) ^ binary_code (I + 1) // 0 <= I <t

 

2. The gray code of integer N is: N ^ (n/2)

 

[Leetcode] 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.