问题描述:
参考代码(java实现):
- import java.util.Scanner;
- import java.lang.Math;
- public class GrayCode{
- public static void main(String[] args)
- {
- int n;
- String[] list;
- Scanner cin;
- cin=new Scanner(System.in);
- n=cin.nextInt();
- if(n>0)
- {
- list=new String[(int)Math.pow(2, n)];
- list[0]="0";
- list[1]="1";
- for(int i=2;i<=n;i++)
- {
- for(int j=(int)Math.pow(2, (i-1));j<(int)Math.pow(2, i);j++)
- {
- list[j]=list[(int)(Math.pow(2,i)-j)-1];
- }
- for(int k=1;k<=(int)Math.pow(2,(i-1));k++)
- {
- list[k-1]="0"+list[k-1];
- list[k-1+(int)Math.pow(2, (i-1))]="1"+list[k-1+(int)Math.pow(2,(i-1))];
- }
- }
- for(int j=0;j<(int)Math.pow(2, n);j++)
- {
- System.out.println(list[j]);
- }
- }
- }
- }
转载于:https://blog.51cto.com/pengjh/568233