Given a positive integer, return its complement. The complement is formed by flipping every bit in the number binary representation, considering only its significant bits (no leading zero bits beyond the highest set bit). Return null for null input.
Examples:
Input: num = 5
Output: 2
Explanation: 5 is 101 in binary; flipping each significant bit gives 010, which is 2
Input: num = 1
Output: 0
Explanation: 1 is 1 in binary; flipping gives 0
Input: num = 7
Output: 0
Explanation: 7 is 111 in binary; flipping all three bits gives 000
Input: num = 10
Output: 5
Explanation: 10 is 1010 in binary; flipping each significant bit gives 0101, which is 5
Input: num = 2
Output: 1
Explanation: 2 is 10 in binary; flipping gives 01, which is 1
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 September 2026 (Sep 16–30)Sponsored by FLXBL
Contest runs September 16 - 30. 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.