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.
思想:格雷码和二进制码之间的转换
参考:wiki 格雷码的介绍 http://zh.wikipedia.org/wiki/%E6%A0%BC%E9%9B%B7%E7%A0%81
第一种方法: 类似于集合的方式,在n-1格雷码的基础上,仅需在最左侧添加1即可,求n格雷码;如下图
实现:
- public ArrayList<Integer> grayCode(int n) {
- ArrayList<Integer> res = new ArrayList<Integer>();
- if(n==0) {
- res.add(0);
- return res;
- }
- if(n==1) {
- res.add(0);
- res.add(1);
- return res;
- }
- res.add(0);
- res.add(1);
- int i=2;
- while(i<=n) {
- int len=res.size();
- int base=(int)Math.pow(2,i-1);
- for(int j=len-1;j>=0;j--) {
- res.add(res.get(j)+base);
- }
- i++;
- }
- return res;
- }
第二种方法:格雷码直接等于二进制 i ^(i>>1)
- public ArrayList<Integer> grayCode(int n) {
- ArrayList<Integer> res = new ArrayList<Integer>();
- for(int i=0;i<(int)Math.pow(2,n);i++) {
- res.add(i^(i>>1));
- }
- return res;
- }
C++代码
- vector<int> grayCode(int n) {
- vector<int> res;
- for(int i=0;i<pow(2,n);i++) {
- res.push_back(i^(i>>1));
- }
- return res;
- }
二进制码和格雷码之间转换,若格雷码为b1b2b3b4b5,则二进制为 a1a2a3a4a5,假设二进制的最左边一位a0=0;
则ai=ai-1 + bi; (i = 1...5)
二进制码第n位 = 二进制码第(n+1)位+格雷码第n位。因为二进制码和格雷码皆有相同位数,所以二进制码可从最高位的左边位元取0,以进行计算,计算过程中无进位。