Given a non-negative integer n, convert its binary representation into the corresponding Gray code and return the decimal value of the resulting Gray code.
Examples:
Input: n = 7
Output: 4
Explanation: The binary representation of 7 is 111. Its Gray code representation is 100, whose decimal value is 4.Input: n = 10
Output: 15
Explanation: The binary representation of 10 is 1010. Its Gray code representation is 1111, whose decimal value is 15.Input: n = 0
Output: 0
Explanation: The binary representation of 0 is 0. Its Gray code representation is also 0, whose decimal value is 0.
The following table shows the conversion of binary code values to gray code values:
| Decimal Value | Binary Equivalent | Gray Code Equivalent | Decimal Value of Gray Code Equivalent |
|---|---|---|---|
| 0 | 000 | 000 | 0 |
| 1 | 001 | 001 | 1 |
| 2 | 010 | 011 | 3 |
| 3 | 011 | 010 | 2 |
| 4 | 100 | 110 | 6 |
| 5 | 101 | 111 | 7 |
| 6 | 110 | 101 | 5 |
| 7 | 111 | 100 | 4 |
8 | 1000 | 1100 | 12 |
9 | 1001 | 1101 | 13 |
10 | 1010 | 1111 | 15 |
Using Bit Manipulation - O(1) Time and O(1) Space
The Gray code of a number can be generated using the property:
Gray Code = n ^ (n >> 1)
Here, n >> 1 represents the number obtained after shifting all bits of n one position to the right. Performing a bitwise XOR between n and (n >> 1) produces the corresponding Gray code.
Consider : n = 10
- Binary representation of 10 is 1010.
- n >> 1 = 0101
- GrayCode = 1010 XOR 0101 = 1111
Decimal value of 1111 is 15.
#include <bits/stdc++.h>
using namespace std;
int binaryToGray(int n) {
// Right shift n by 1 bit
int res = n >> 1;
// XOR with original number to get Gray code
return n ^ res;
}
int main()
{
int n = 10;
cout << binaryToGray(n) << endl;
return 0;
}
#include <stdio.h>
int binaryToGray(int n) {
// Right shift n by 1 bit
int res = n >> 1;
// XOR with original number to get Gray code
return n ^ res;
}
int main() {
int n = 10;
printf("%d\n", binaryToGray(n));
return 0;
}
class GFG {
public static int binaryToGray(int n) {
// Right shift n by 1 bit
int res = n >> 1;
// XOR with original number to get Gray code
return n ^ res;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(binaryToGray(n));
}
}
def binaryToGray(n):
# Right shift n by 1 bit
res = n >> 1
# XOR with original number to get Gray code
return n ^ res
if __name__ == "__main__":
n = 10
print(binaryToGray(n))
using System;
class GFG {
static int binaryToGray(int n) {
// Right shift n by 1 bit
int res = n >> 1;
// XOR with original number to get Gray code
return n ^ res;
}
public static void Main ()
{
int n = 10;
Console.WriteLine(binaryToGray(n));
}
}
function binaryToGray(n) {
// Right shift n by 1 bit
let res = n >> 1;
// XOR with original number to get Gray code
return n ^ res;
}
//Driver code
let n = 10;
console.log(binaryToGray(n));
Output
15