1+ import java .util .Arrays ;
2+
13/**
24 * Created with IntelliJ IDEA.
35 * Print the N-bit binary reflected Gray code using recursion.
@@ -16,6 +18,7 @@ public class GrayCode {
1618 public static void main (String [] args ) {
1719 int N = 3 ;
1820 grayCode (N , new boolean [N ]);
21+ grayCode (N );
1922 }
2023
2124 public static void grayCode (int n , boolean [] show ) {
@@ -54,4 +57,39 @@ public static void showCode(boolean[] show) {
5457 // System.out.println(Integer.parseInt(code, 2));
5558 }
5659
60+ /*
61+ ** The BinaryToGray method is base on the bit of gray cod loop occur: 0,1,1,0
62+ ** Hence, we could calculate each bits of gray code by mod 4 to find the matching value
63+ **
64+ ** However, after search on the website, the convert formula is just simply as (i>>1) ^ i.
65+ ** The ith bit is equal to ith bit plus (i+1)th bit with no carry.
66+ */
67+
68+ public static String [] grayCode (int n ) {
69+ int [] code = new int [1 << n ];
70+ String [] codeString = new String [1 << n ];
71+
72+ for (int i = 0 ; i < (1 << n ); i ++) {
73+ code [i ] = (i >> 1 ) ^ i ;
74+ // codeString[i] = Integer.toBinaryString((i >> 1) ^ i);
75+ codeString [i ] = toBinaryString ((i >> 1 ) ^ i );
76+ }
77+
78+ System .out .println (Arrays .toString (codeString ));
79+ System .out .println (Arrays .toString (code ));
80+
81+ return codeString ;
82+ }
83+
84+ public static String toBinaryString (int integer ) {
85+ StringBuilder builder = new StringBuilder ();
86+ int temp ;
87+ while (integer > 0 ) {
88+ temp = integer ;
89+ integer = (temp >> 1 );
90+ builder .append (temp % 2 );
91+ }
92+ return builder .reverse ().toString ();
93+ }
94+
5795}
0 commit comments