Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
Java 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, given a=101 and b=111 (in binary), the a&b=101. a&b << 1 = 1010.
a^b is the number formed by different bits of a and b. a&b=10.
public int getSum(int a, int b) { while(b!=0){ int c = a&b; a=a^b; b=c<<1; } return a; } |
Lol yeah hahahahahahaha
Ok, I understood how it works. If to use regular math, you need to break each of 2 numbers into a sum like (…32+16+8+4+2+1). For example, if we want to add 21 and 37, we break 21=(16+4+1); 33=(32+4+1).
Then we split these into 2 groups: group A duplicate components {+4 +1}; group B single components {+16 +32}.
We multiply duplicate components by 2 and keep single components as is, group A 5 * 2 = 10; group B 16 + 32 = 48.
Now instead of adding 21 and 37, we want to add 10 and 48, but now it is easier. We break these numbers again: 10=(8+2); 48=(32+16). No duplicate components, we stop the loop and just add these 2 numbers using ^: 10+48=58.
This works because operator & finds duplicate components (21 & 37 finds +4 and +1 in our case), operator <<1 multiplies them by 2, operator ^ adds 2 numbers if they don't have duplicate components (10 ^ 48 = 58 in our case).
a– is a = a -1
so you are still using + – operators
if we could use operator ++ and — then following solution would work
public static int sum(int a, int b) {
while (b != 0) {
if (b < 0) {
a--;
b++;
} else {
a++;
b--;
}
}
return a;
}