格雷码
the n-1 bit code, with 0 prepended to each word, followd by the n-1 bit code in reverse order,
with 1 prepended to each word.
public class GrayCode{ public static void gray(int n, String prefix) { if(n == 0) System.out.println(prefix); else { gray(n-1,prefix + "0"); yarg(n-1,prefix + "1"); } } public static void yarg(int n, String prefix) { if(n == 0) System.out.println(prefix); else { gray(n-1,prefix + "1"); yarg(n-1,prefix + "0"); } } public static void main(String[] args) { int N = Integer.parseInt(args[0]); gray(N, ""); } }
运行结果
> java GrayCode 3 000 001 011 010 110 111 101 100