Gray Code
The gray code is a binary numeral system where two successive
values 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] 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.
|
Analysis:
Write by hand 00, 01, 11, 10, 110, 111, 101, 100
The position changes is at 0,1,0,2,0,1,0
You find something?
Yes, it's symmetric!
The only thing we need to do is get the bit position as vector, and change bit according to it!
The bit_to_change is generated by A(n) = A(n-1) + n + A(n-1), by concatenation.
Yeah, later I found that there is a formula to generate Gray Code for each number as Gray(n) = (n>>1)^n.
But I still find my method is more interesting, LOL.
Code says!
class Solution {
public:
std::vector<int> grayCode(int n) {
std::vector<int> ret;
std::vector<int>& bit_to_chage = get_bit_to_change(n-1);
int num = 0;
ret.push_back(num);
for(int i=0; i<bit_to_chage.size(); i++)
{
num ^= 1<<bit_to_chage[i];
ret.push_back(num);
}
return ret;
}
std::vector<int> get_bit_to_change(int n)
{
std::vector<int> ret;
if(n<0)
return ret;
std::vector<int>& v = get_bit_to_change(n-1);
ret.insert(ret.end(), v.begin(), v.end());
ret.push_back(n);
ret.insert(ret.end(), v.begin(), v.end());
return ret;
}
};
No comments:
Post a Comment