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