格雷码

来源:互联网 发布:东晋历史知乎 编辑:程序博客网 时间:2024/05/22 17:15

格雷码是一种特殊的二进制编码格式,其特殊之处在于相邻的码之间只有一位是不同的,比如说2位的格雷码编码如下:00,01,11,10。现在任给n,要求输出n位的格雷码。

思路如下:以x表示格雷码序列,第一位不变,其余位变化得到n-1位的格雷码,然后第一位取反,再接着n-1位变化。这里主要是考虑到格雷码的特性——循环。

代码如下:

class GreyCode{//输出n位的格雷码public static void test(){grey(1);grey(2);grey(4);}public static void grey(int n){if(n<=0)return;boolean[]codes=new boolean[n];grey(codes,0);}private static void out(boolean[]codes){StringBuilder sb=new StringBuilder(codes.length);for(boolean b:codes)if(b)sb.append(1);elsesb.append(0);System.out.println(sb.toString());}private static void grey(boolean[]codes,int w){if (w == codes.length - 1) {out(codes);codes[w] = !codes[w];out(codes);} else {grey(codes, w + 1);codes[w] = !codes[w];grey(codes, w + 1);}}}


原创粉丝点击