Number Complement

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Number Complement

Approach

Count the number of significant bits in the number, then create a mask of all 1s with that length using (1 << bits) - 1. XOR the number with the mask to flip every bit within the significant range.

Complexity Analysis

Time
O(log n)
Space
O(1)

Pattern

Bit Masking

Why It Works

XOR with a mask of all 1s flips each bit (0 becomes 1, 1 becomes 0), producing the complement within the number's actual bit width rather than the full 32-bit width.

Updated Mar 2026