Sum of two integers without plus operator

Problem:
Calculate the sum of two integers a and b, but you are not supposed to use + operator. For example, given a=1 and b=2, return 3.

Solution:
Given two numbers a and b, a&b returns the number formed by 1 bits on a and b. When it is left shifted by 1 bit, it is the carry.
For example, give a = 101 and b = 111(binary), a&b = 101. a&b << 1 =1010. a^b is the number formed by different bits of a and b. a&b=10.

package com.algorithm.twosum;

public class TwoSumWithoutPlusOperator {

    public static void main(String[] args) {
        System.out.println("Sum of a and b is: " + getSum(1, 2));
    }

    private static int getSum(int a, int b) {
        while (b != 0) {
            int c = a & b;
            a = a ^ b;
            b = c << 1;
        }
        return a;
    }
}

As per the above, the output is like Sum of a and b is: 3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s