"One Day together Leetcode" #89. Gray Code

Source: Internet
Author: User

One Day together Leetcode

This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source

(i) Title

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-0
01-1
11-3
10-2

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

For example, [0,2,3,1] was 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.

(ii) Problem solving

Topic: Given an integer n, generates an n-bit gray code.

Before the problem of gray code, each time in the n-1 bit gray code behind plus 0 and 1 composed of n-bit gray code.

The title refers only to the sequence of gray codes given in the example.

Therefore, it is easy to find the law, each time from the n-1 bit gray code tail forward, followed by a 2 of the n-1 to get the new n-bit gray code.

The code is as follows:

classSolution { Public: vector<int>Graycode (intN) { vector<int>Retif(n==0) {//For 0, special handling is requiredRet.push_back (0);returnRet } for(inti =0; I < n; i++) {if(i==0)//Here represents 1-bit gray code{Ret.push_back (0); Ret.push_back (1); }Else{ for(intj = ret.size ()-1; J >=0; j--)//each time from the tail of the n-1-bit gray code to forward, once plus 2 of the n-1 to get the new gray code{Ret.push_back (POW(2, i) +ret[j]); }            }        }returnRet }};

"One Day together Leetcode" #89. 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.