Skip to main content
Back to problems
Leetcode
Easy
Bit Manipulation
Math
Complement Of Base 10 Integer

Return the base-10 complement of a non-negative integer by flipping every bit in its binary representation up to the highest set bit.

Acceptance 80%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

Problem

Given a non-negative integer num, compute its bitwise complement in base 10.

The complement is formed by taking the binary representation of num, flipping every bit from the most significant 1 down to the least significant bit, and converting the result back to decimal.

For example, if num = 5, its binary form is 101, so the complement is 010, which equals 2.

Notes

  • Leading zeros are not considered part of the representation.
  • If num = 0, treat its complement as 1.

Input Format

  • A single non-negative integer num.

Output Format

  • Return the decimal value of the bitwise complement of num.

Constraints

  • 0 <= num < $2^{31}$

Hints

  • Find the smallest all-ones mask that covers the binary length of num.
  • Then XOR that mask with num to flip only the significant bits.

Input Format

  • A single integer num.

Output Format

  • A single integer: the complement of num.

Constraints

  • 0 <= num < $2^{31}$
  • The answer fits in a 32-bit signed integer.
Examples
Sample cases returned by the problem API.

Example 1

Input

num = 5

Output

2

Explanation

5 is 101 in binary. Flipping the three significant bits gives 010, which is 2.

Example 2

Input

num = 1

Output

0

Explanation

1 is 1 in binary. Flipping that bit gives 0.

Show 1 more example

Example 3

Input

num = 0

Output

1

Explanation

By convention for this problem, the complement of 0 is 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.