gpt4 book ai didi

java - 优化java中的变量检查

转载 作者:行者123 更新时间:2023-11-30 03:28:16 25 4
gpt4 key购买 nike

我最近一直在进行codingbat练习,这是我对其中一个问题的解决方案

public boolean makes10(int a, int b) {
return (a == 10 || b == 10 || a+b == 10);
}

代码本身可以工作,但我想知道是否可以进一步优化该代码,因为 2 个变量(a 和 b)都检查它们是否等于相同的值。我指的是 a == 10 || b == 10

最佳答案

当 if block 中的第一个条件返回 true 时,它​​不会移动到下一个条件 true || false = truetrue || true = true 即,如果第一个参数为 true,则第二个参数不计算,因为整个表达式必须为 true。因此,就优化而言,您现在的代码很好。该行为称为short circuit evaluation

来自docs :

The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. [...] At run time, the left-hand operand expression is evaluated first; [...] if the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated; [...] the resulting value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

关于java - 优化java中的变量检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29667333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com