Title Description: (link)
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-001-111-310-2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, was [0,2,3,1]
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.
Problem Solving Ideas:
This topic requires a mathematical formula for the gray code of all n-bit gray code sequences, integer n:n ^ (N/2).
1 classSolution {2 Public:3vector<int> Graycode (intN) {4vector<int>result;5 intSize =1<<N;6 result.reserve (size);7 for(inti =0; i < size; ++i) {8Result.push_back ((i ^ (i >>1)));9 }Ten One returnresult; A } -};
[Leetcode] Gray Code