Bit Manipulation · Easy

Clear the Rightmost Set Bit

Solve it on DeVert Campus - free code runner

Problem

Given a non-negative integer N, clear (turn off) its rightmost set bit - the lowest-order bit that is currently 1 - and print the resulting value. If N has no set bits (N is 0), print 0.

Input and output

Input: A single line containing the integer N. Output: A single line containing N with its rightmost set bit cleared.

Example

Input:
12
Output:
8

Constraints

0 <= N <= 2^31 - 1 (2147483647)

Key observation

This formula naturally handles N=0 correctly without any special-casing - 0 & (0-1) still evaluates to 0, since there's no set bit to clear in the first place.

Intuition

Turn off the lowest 1-bit of a number, leaving everything else unchanged. Brute force: Scan bits from the least significant one upward, checking each for being the first 1-bit, then explicitly clear just that one - this works but takes multiple steps when a single bitwise operation does the whole job at once. Optimised: Subtracting 1 from N flips every bit from the rightmost set bit DOWNWARD (turning that set bit off and every 0 below it into a 1), while leaving everything ABOVE it unchanged - ANDing this with the original N then keeps only the UNCHANGED upper bits, effectively clearing just that lowest set bit, in a single O(1) operation.

Step by step

1. Compute N & (N - 1). 2. This single operation always clears exactly the lowest set bit of N, regardless of the rest of N's bit pattern.

Complexity

Time: O(1) - a single bitwise AND and subtraction. Space: O(1) - no extra storage.

Edge cases

N = 0 has no set bits and must print 0; when N is itself a power of two, clearing its only set bit produces 0.

Interview tip

Be ready to explain WHY N & (N-1) works by tracing through the binary subtraction's borrow behavior - this exact trick (N & (N-1)) is also the foundation of the classic 'count set bits' and 'is power of two' bit tricks.

All DSA problems