野心家

导航

格雷码示例

package java1;
import java.util.*;
public class Java1 {

    public static void main(String[] args) {
        
        System.out.println("请输入一个正整数:");
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        String[] getReturn = gray(n);
        System.out.println("格雷码为:");
        for(int i=0;i<Math.pow(2, n);i++){
        if(i%5==0){
            System.out.println();
        }
        System.out.print(getReturn[i]+"  ");
        
        }
    }
    
    public static String[] gray(int n){
         
            // produce 2^n grade codes  
            String[] graycode = new String[(int) Math.pow(2, n)];            
            if (n == 1) {  
                graycode[0] = "0";  
                graycode[1] = "1";  
                return graycode;  
            }            
            String[] last = gray(n - 1);            
            for (int i = 0; i < last.length; i++) {  
                graycode[i] = "0" + last[i];  
                graycode[graycode.length - 1 - i] = "1" + last[i];  
            }      
            return graycode;
            
         
    }
}

  

posted on 2017-12-03 23:30  野心家  阅读(203)  评论(0编辑  收藏  举报