The Gray code is a binary numeral system where two successive values differ in only one bit.
Given an integer n
representing the total number of bits in the code, return any sequence of Gray code. A Gray code sequence must begin with 0.
Example 1:
Input: n = 2
Output: [0,1,3,2]
Explanation:
0 - 00
1 - 01
3 - 11
2 - 10
[0,1,3,2] is a Gray code sequence that meets the requirement for n = 2. Another valid sequence is [0,2,3,1].
Example 2:
Input: n = 1
Output: [0,1]
Constraints:
1 <= n <= 16
i
, its Gray code can be obtained by G(i) = i ^ (i >> 1)
, where ^
denotes the bitwise XOR operator, and >>
denotes the right shift operator.0
to 2^n - 1
, and for each number, apply the Gray code transformation i ^ (i >> 1)
.import java.util.*;
public class GrayCode {
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<>();
int numberOfGrayCodes = 1 << n; // 2^n
for (int i = 0; i < numberOfGrayCodes; i++) {
result.add(i ^ (i >> 1));
}
return result;
}
public static void main(String[] args) {
GrayCode gc = new GrayCode();
System.out.println(gc.grayCode(2)); // Output: [0, 1, 3, 2]
System.out.println(gc.grayCode(1)); // Output: [0, 1]
}
}
O(2^n)
where n
is the number of bits, since we generate 2^n
Gray code numbers.O(2^n)
for storing the result list which includes all the generated Gray codes.By following this strategy and code, you can generate a valid sequence of Gray code for any integer n
within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?