Invert the Active Bits

EasyBit Manipulation

Problem

A display shows the positive integer value in binary with no leading zeros. Pressing the invert button flips every digit on screen: each 1 becomes 0 and each 0 becomes 1. The screen width does not change, so only the digits currently shown are flipped.

Return the integer the screen shows after one press.

Example 1

Input:
value = 5
Output:
2

101 becomes 010, which is 2.

Example 2

Input:
value = 1
Output:
0

Example 3

Input:
value = 10
Output:
5

1010 becomes 0101.

Constraints

  • 1 ≤ value < 2^31

Hint

Show the first hint

Plain bitwise NOT flips the leading zeros too. How do you flip only the shown digits?

Walkthrough

How to approach it

01Clarify before coding

  • Can value be 0? No, value ≥ 1, so there is always at least one digit on screen.
  • Is the result allowed to have leading zeros? Yes, it is just returned as a number: 101 → 010 = 2.

02Brute force

Convert to a binary string, swap '0' and '1' characters and parse the string back.

Cost: O(log value) time and space for the string; it works but uses string manipulation for a pure bit task.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.