I am solving an interview question which is to write a method that does the addition of two digits without using the + operator.
I understand the algorithm very well and I can do it easily in C.
Here is the algorithm and it works perfectly:
int add(int x, int y) {
int a, b;
do {
a = x & y;
b = x ^ y;
x = a << 1;
y = b;
} while (a);
return b;
}
I tried translating this code to Java, but this algorithm functions because a is going to become 000 at one point which in C will equal to False in the while loop. What is the alternative for that in Java?
Thanks.
You need to use a boolean for the condition in Java:
while (a != 0)
Edit (full code):
int add(int x, int y) {
int a, b;
do {
a = x & y;
b = x ^ y;
x = a << 1;
y = b;
} while (a != 0);
return b;
}
Java does not - unlike C - interprete 0
as false
. As stated in my comment you have to use a boolean expression such as:
while (a != 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.