# Javascript solution

• ``````English is poor, translate the following passage by google translate
// In addition to the most significant bit (left first), Gray code bits completely vertically symmetrical (see list below). For example, the first and the last Gray code Gray code symmetrical (except the first one), the second with a second gray code inverse of symmetry, and so on.
// Step 1: to produce 0, 1 two strings.
// Step 2: In the first step on the basis of each of strings plus 0 and 1, but you can only add one, so you have to do twice. This becomes 00,01,11,10 (note symmetric).
// Step 3: On the basis of the second step, to give each string plus 0 and 1, the same, you can only add one, so it becomes a 000,001,011,010,110,111,101,100.
// Okay, three yuan Gray code down.
// If you want to generate four yuan Gray code, we only need the three yuan Gray code plus a layer 0,1 can be: 0000,0001,0011,0010,0110,0111,0101,0100,1100,1101, 1110,1010,0111,1001,1000.
the solution:
var grayCode = function(n) {
var result = [];

var graycodeFn = function(n){
var graycode = [];

if(n == 1){
graycode[0] = "0";
graycode[1] = "1";
return graycode;
}

var last = arguments.callee(n-1);	// arguments.callee(n-1) == graycodeFn(n-1)

for(var i=last.length-1; i>=0; --i){
graycode.unshift("0"+last[i]);
graycode.push("1"+last[i]);
}

return graycode;
}

var graycode = (n==0)?["0"]:graycodeFn(n);

for(var i=0; i<graycode.length; ++i){
result.push(parseInt(parseInt(graycode[i], 2), 10)); // String To Number
}

return result;
}``````

• Realization Gray code

``````[java]
public String[] GrayCode(int n) {

String[] graycode = new String[(int) Math.pow(2, n)];

if (n == 1) {
graycode[0] = "0";
graycode[1] = "1";
return graycode;
}

String[] last = GrayCode(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;
}

[javascript]
var graycodeFn = function(n){
var graycode = new Array(Math.pow(2, n));
// When leetcode.com test occurred Invalid array length. So changed, var graycode = [];

if(n == 1){
graycode[0] = "0";
graycode[1] = "1";
return graycode;
}

var last = arguments.callee(n-1);

for(var i=0; i<last.length; ++i){ // changed, for(var i=last.length-1; i>=0; --i){
graycode[i] = "0" + last[i];	// changed, graycode.unshift("0"+last[i]);
graycode[graycode.length-i-1] = "1" + last[i]; // changed, graycode.push("1"+last[i]);
}

return graycode;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.