[編程題] 生成格雷碼(JAVA實現)

在一組數的編碼中,若任意兩個相鄰的代碼只有一位二進制數不同, 則稱這種編碼爲格雷碼(Gray Code),請編寫一個函數,使用遞歸的方法生成N位的格雷碼。

給定一個整數n,請返回n位的格雷碼,順序爲從0開始。

測試樣例:
1
返回:["0","1"]
分析:實際就是將二進制數進行合理的排序找規律
代碼如下:


/**
		    * n=1 0 1
		    * n=2 00 01 11 10
		    * ....
		    * 分析高位爲0時與n-1的所有情況一致,爲1時逆序
		    */
	       if(n<=0) return new String[]{};
	       String[] result=new String[(int) Math.pow(2, n)];
	      if(n>=1) {result[0]="0"; result[1]="1";}
	       for(int i=2;i<=n;i++){
	    	   int temp=(int)Math.pow(2, i);
	    	   for(int j=temp/2;j<temp;j++){//後半部分
	    		   result[j]="1"+result[temp-j];
	    	   }
	    	   for(int j=0;j<temp/2;j++){//前半部分
	    		   result[j]="0"+result[j];
	    	   }
	       }
	       return result;


發佈了54 篇原創文章 · 獲贊 66 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章