887788. Subtract 1 using Bitwise operators

Easy

Subtract 1 without using Arithmetic Operators

Summary

Given an integer, write a function that subtracts 1 from it without using arithmetic operators (i.e., no subtraction, addition, multiplication, or division). This problem requires creative use of bitwise operations to achieve the desired result. The key concepts involved are bitwise operators and their properties.

Detailed Explanation


The approach is to use bitwise XOR (^) operation to subtract 1 from a given number. Here's the step-by-step breakdown:

  1. Convert the integer to binary form.
  2. For each bit position, perform a bitwise XOR operation with the original value and the value obtained by flipping all bits (i.e., inverting the bits).
  3. The result of the XOR operation is the original value minus 1.

Here's an example:

View on GeeksforGeeks
public int subtractOne(int n) {
    return n ^ (n >> 31);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.