
Sponsored
Sponsored
Gray code can be generated using a simple bit manipulation technique. For a given integer k, the corresponding Gray code is obtained by XORing k with (k >> 1). This technique ensures that each step in changing numbers results in transitioning only one bit.
Time complexity: O(2n), traversing all numbers.
Space complexity: O(1), using constant extra space.
1public class GrayCode {
2 public static void main(String[] args) {
3 int n = 2;
4 grayCode(n);
5 }
6
7 public static void grayCode(int n) {
8 int size = (int) Math.pow(2, n);
9 for (int i = 0; i < size; i++) {
10 int gray = i ^ (i >> 1);
11 System.out.print(gray + " ");
12 }
13 }
14}This Java program uses bit manipulation to print Gray code series by iterating from 0 to 2n - 1, calculating each Gray code value using the expression i ^ (i >> 1).
The Gray code can be recursively generated by reflecting the existing sequence. Start with a base case of n=1: [0,1]. For each subsequent n, reflect the current list, prepend a bit to the reflected part, and concatenate the results: if Gn-1 = [0, 1], then Gn = [0Gn-1, 1Gn-1].
Time complexity: O(2n), where recursions reflect and build upon previous results.
Space complexity: O(2n), allocating for the result array.
1
This JavaScript solution recursively generates Gray code by leveraging reflection, creating a concatenation of results for incoming sequences, managing states efficiently in an array.