All problems
Binary to Gray
Problem
Convert a nonnegative integer to its Gray code representation:
gray = n ^ (n >> 1)
Adjacent integers map to Gray codes that differ in exactly one bit.
Hint
XOR each bit with the next more significant bit.
Test cases
case 1
in: [0]
expected: 0
case 2
in: [1]
expected: 1
case 3
in: [2]
expected: 3
case 4
in: [3]
expected: 2
case 5
in: [7]
expected: 4
case 6
in: [15]
expected: 8
Starter codePython
def binary_to_gray(n):
# Your code here
pass6 test cases · run your code against them in the editor