Complement of Base 10 Integer

Easy Bit Manipulation

Problem

Return the bitwise complement of N using only as many bits as the binary representation of N (no leading-zero flips).

Example 1 Input: 5 Output: 2 Explain: 101 → 010
Example 2 Input: 7 Output: 0 Explain: 111 → 000
Example 3 Input: 0 Output: 1

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def bitwiseComplement(self, N):
        if N == 0:
            return 1
        mask = (1 << N.bit_length()) - 1
        return N ^ mask

Java

class Solution {
    public int bitwiseComplement(int N) {
        if (N == 0) return 1;
        int mask = 1;
        while (mask < N) mask = (mask << 1) | 1;
        return N ^ mask;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Complement of Base 10 Integer interactively → ← All solutions