Given a non-negative integer n, return its Gray code equivalent. The Gray code of a number is obtained by taking the bitwise XOR of the number with itself shifted right by one bit: gray = n ^ (n >> 1). Gray codes are an ordering of binary numbers where two successive values differ in only one bit.
Examples:
Input: n = 0
Output: 0
Explanation: 0 ^ 0 = 0
Input: n = 1
Output: 1
Explanation: 1 ^ 0 = 1
Input: n = 2
Output: 3
Explanation: binary 10 ^ 01 = 11 which is 3
Input: n = 4
Output: 6
Explanation: binary 100 ^ 010 = 110 which is 6
Input: n = 10
Output: 15
Explanation: binary 1010 ^ 0101 = 1111 which is 15
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay November 2026 (Nov 1–15)Sponsored by FLXBL
Contest runs November 1 - 15. Complete challenges to climb the leaderboard!
Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes
Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.