easy +10 pts

Gray Code Encode

Convert a non-negative integer to its Gray code equivalent using bitwise XOR and shift.

Write a function `gray_encode(n: int) -> int` that takes a non-negative integer `n` and returns its Gray code equivalent. The Gray code of a number `n` is computed as `n XOR (n >> 1)`. This produces a reflected binary Gray code where consecutive values differ in exactly one bit. Your function should handle any non-negative integer within the standard Python integer range (arbitrary precision).

Constraints

- `0 <= n <= 10**9` (but the formula works for any non-negative integer) - Time complexity: O(1) - Space complexity: O(1)

Example

>>> gray_encode(0)
0
>>> gray_encode(1)
1
>>> gray_encode(2)
3
>>> gray_encode(3)
2
>>> gray_encode(4)
6
>>> gray_encode(5)
7
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

The Gray code formula is a single bitwise expression.
Think about the XOR operation and right shift.
For `n=2` (binary 10), the Gray code should be 3 (binary 11).
No loops needed.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.