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格雷码;如下图

实现:

  1. public ArrayList<Integer> grayCode(int n) {
  2. ArrayList<Integer> res = new ArrayList<Integer>();
  3. if(n==0) {
  4. res.add(0);
  5. return res;
  6. }
  7. if(n==1) {
  8. res.add(0);
  9. res.add(1);
  10. return res;
  11. }
  12. res.add(0);
  13. res.add(1);
  14. int i=2;
  15. while(i<=n) {
  16. int len=res.size();
  17. int base=(int)Math.pow(2,i-1);
  18. for(int j=len-1;j>=0;j--) {
  19. res.add(res.get(j)+base);
  20. }
  21. i++;
  22. }
  23. return res;
  24. }

第二种方法:格雷码直接等于二进制 i ^(i>>1)

  1. public ArrayList<Integer> grayCode(int n) {
  2. ArrayList<Integer> res = new ArrayList<Integer>();
  3. for(int i=0;i<(int)Math.pow(2,n);i++) {
  4. res.add(i^(i>>1));
  5. }
  6. return res;
  7. }

 C++代码

  1. vector<int> grayCode(int n) {
  2. vector<int> res;
  3. for(int i=0;i<pow(2,n);i++) {
  4. res.push_back(i^(i>>1));
  5. }
  6. return res;
  7. }

二进制码和格雷码之间转换,若格雷码为b1b2b3b4b5,则二进制为 a1a2a3a4a5,假设二进制的最左边一位a0=0;

则ai=ai-1 + bi; (i = 1...5)

二进制码第n位 = 二进制码第(n+1)位+格雷码第n位。因为二进制码和格雷码皆有相同位数,所以二进制码可从最高位的左边位元取0,以进行计算,计算过程中无进位。

 

posted @ 2014-06-23 23:46  purejade  阅读(107)  评论(0编辑  收藏  举报