Java Program of Calculating the Sum of Two Integers without using + - operator

When it comes to adding two integers without using the standard + or - operators, a bit of manipulation technique comes to the rescue.

This technique is based on the idea of simulating the addition process using bitwise operations, specifically using the bitwise AND, XOR, and left shift (<<) operators.

The Bit Manipulation Approach

We'll be working with two integers, a and b. The goal is to add them together without using the + operator.

Here's how it works:

  1. Use the bitwise XOR (^)  the operation to calculate the sum of the integers without considering the carry:
  
    a ^ b
    
  1. Use the bitwise AND (&) the operation followed by left shifting (<<) to calculate the carry:
   
    (a & b) << 1
    
  1. Add the sum from step 1 and the carry from step 2:
    
    (a ^ b) + ((a & b) << 1)
    

Example:

Let's consider a = 5 and b = 3:

  
    a = 0101
    b = 0011
    

Step 1 - Calculate the sum using XOR:

  
    a ^ b = 0110 (6 in decimal)
    

Step 2 - Calculate carry using AND and left shift:

  
    (a & b) << 1 = 0010 (2 in decimal)
    

Step 3 - Add sum and carry:

   
    (a ^ b) + ((a & b) << 1) = 0110 + 0010 = 1000 (8 in decimal)
    

Code

       
    
    class Solution {
        public int getSum(int a, int b) {
            if(a == 0){ return b;}
            if(b == 0){ return a;}
            
            int sum = -1, carry = b;
            
            while(carry != 0) {
                sum = a ^ b;   // XOR Operation
                carry = (a & b) << 1;   // And operation and one left shift the bits

                a = sum;
                b = carry;
            }
            return sum;
        }
    }
    
    
    

Post a Comment

0 Comments