Leetcode: Gray Code

Source: Internet
Author: User

Leetcode: Gray Code

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.

Address: https://oj.leetcode.com/problems/gray-code/

Algorithm: assuming that we have completed the first I-bit gray code, we should construct the first I + 1-bit gray according to the following structure: first, the I + 1-bit zero part, the subsequent I-bit is the same as the previous I-bit gray code, followed by the part where I + 1 is 1, the second I-bit is sorted in the reverse order of the first I-bit gray code. If the n = 2gray code is 00 01 11 10, then the Gray Code of N = 3 is 000 001 011 010 110 111 101 100. Code:

 1 class Solution { 2 public: 3     vector<int> grayCode(int n) { 4         vector<int> result; 5         if(n < 0)   return result; 6         result.push_back(0); 7         if(n == 0)  return result; 8         result.push_back(1); 9         for(int i = 1; i < n; ++i){10             int len = result.size();11             int temp = 1 << i;12             for(int j = len-1; j >= 0; --j){13                 result.push_back(result[j] + temp);14             }15         }16         return result;17     }18 };

 

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.