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:
- Convert the integer to binary form.
- 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).
- The result of the XOR operation is the original value minus 1.
Here's an example:
public int subtractOne(int n) {
return n ^ (n >> 31);
}