Given a value N and K, the task is to generate N-bits Gray Code starting from the value K.
Input: N = 2, K = 3
Output: 3 2 0 1
3 -> 11
2 -> 10
0 -> 00
1 -> 01
Each value differ by only one bit from the next value in their binary representation.
Input: N = 3, K = 2
Output: 2 3 1 0 4 5 7 6
- Gray code are numbers with hamming distance 1 between two consecutive numbers in it.
- The XOR with each element of N bit Gray code generates a sequence of Hamming distance of 1.
- As the first element of N bit Gray code is K, it can be obtained by doing is XOR with 0, i.e. (K ^ 0) = K.
- So the sequence will start with 0 with every consecutive element differ by only one bit in their binary representation.
Below is the implementation of the above approach:
2 3 1 0 4 5 7 6
- Subset array sum by generating all the subsets
- Reverse an array without using subtract sign ‘-‘ anywhere in the code
- Decimal Equivalent of Gray Code and its Inverse
- Lucky alive person in a circle | Code Solution to sword puzzle
- Check if original Array is retained after performing XOR with M exactly K times
- Count number of binary strings without consecutive 1’s : Set 2
- Bitwise Operations on Digits of a Number
- Maximum value of B less than A such that A ^ B = A + B
- Count of even and odd set bit with array element after XOR with K
- Count of even set bits between XOR of two arrays
- Print all possible pair with prime XOR in the Array
- XOR of two Binary Strings
- Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity
- Number of integers in a range [L, R] which are divisible by exactly K of it's digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnkitRai01