简体   繁体   English

Java中while(0)或while(1)的替代方法是什么?

[英]What is the alternative for while(0) or while(1) in Java?

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. 我对算法非常了解,可以在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. 我尝试将这段代码转换为Java,但是该算法起作用了,因为a将在某一点变为000,而在while循环中C等于False。 What is the alternative for that in Java? Java的替代方法是什么?

Thanks. 谢谢。

You need to use a boolean for the condition in Java: 您需要为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 . Java没有-与C不同-将0解释为false As stated in my comment you have to use a boolean expression such as: 如我的评论所述,您必须使用布尔表达式,例如:

while (a != 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM