Leetcode: Gray Code

Source: Internet
Author: User

Leetcode: Gray Code

I. Question

Input n to output the Gray code of this number.

For example, input 2 and return {0, 1, 3, 2}

Ii. Analysis

1. Binary Code-> gray code (encoding): Starting from the rightmost bit, each bit is in turn different from the one on the left or (XOR ), as the value corresponding to the gray code, the leftmost digit remains unchanged (equivalent to 0 on the left); (corresponding to the loop body in the for loop of the above Code ).

Gray code-> binary code (Decoding): Each decoded value is different from the decoded value of the second digit on the left or, the decoded value (the leftmost one remains unchanged ).

2. Search for rules

Take the three-digit Gray Code as an example.

0 0 0

0 0 1

0 1 1

0 1 0

1 1 0

1 1 1

1 0 1

1 0 0

We can see that the nth Gray Code consists of two parts: one part is the n-1 Gray code, plus the inverse sum of the 1 <(n-1) and n-1 Gray Codes.

As follows:

(0) 00

(0) 01

(0) 11

(0) 10

100 + 010 = 110

100 + 011 = 111

100 + 001 = 101

100 + 000 = 100

class Solution {public:    vector
 
   grayCode(int n) {        int num = 1<
  
    ans;ans.reserve(num);for(int i=0;i
   
    >1));return ans;     }};
   
  
 

class Solution {public:    vector
 
   grayCode(int n) {        vector
  
    ans;        if(n==0){        ans.push_back(0);        return ans;        }        vector
   
     res = grayCode(n-1);         int len = res.size()-1;        int adder = 1<<(n-1);        for(int i=len;i>=0;i--){        res.push_back(adder+res[i]);        }        return res;    }};
   
  
 


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.