首页 > 其他 > 详细

Gray Code

时间:2014-04-10 18:32:28      阅读:536      评论:0      收藏:0      [点我收藏+]

[leetcode]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

 

Gray Code, 每次看每次都不记得。写下来让自己好温习。

Gray Code 0 = 0, 下一项是toggle最右边的bit(LSB), 再下一项是toggle最右边值为 “1” bit的左边一个bit。然后重复

如: 3bit

Gray Code:  000, 001, 011, 010110, 111, 101, 100, 最右边值为 “1” 的bit在最左边了,结束。

Binary      :  000, 001, 010, 011, 100, 101, 110, 111

 

再者就是Binary Code 转换为Gray Code了。

如:

  Binary Code :1011 要转换成Gray Code

  1011 = 1(照写第一位), 1(第一位与第二位异或 1^0 = 1), 1(第二位异或第三位, 0^1=1), 0 (1^1 =0) = 1110

  其实就等于 (1011 >> 1) ^ 1011 = 1110

有了上面的等式写code就简单了

 

bubuko.com,布布扣
1     public ArrayList<Integer> grayCode(int n) {
2         int size=1<<n;
3         ArrayList<Integer> result=new ArrayList<>(size);
4         for(int i=0;i<size;i++)
5         {
6             result.add(i^(i>>1));
7         }
8         return result;
9     }
bubuko.com,布布扣

http://www.cnblogs.com/lihaozy/archive/2012/12/31/2840437.html

Gray Code,布布扣,bubuko.com

Gray Code

原文:http://www.cnblogs.com/friends-wf/p/3655895.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!