最少的代码,缩短表达
给出以下参数:
boolean a = true ;
boolean b = false ;
boolean c = true ;
我想要这个版本的最少代码:
if ( ( a && ! b) || ( ! a && b) ) {
z1 += 99 ;
}
if (a ^ b) {
z1 += 19 ;
}
if ( ( a && b) || ( ! a && ! b) ) {
z1 += 118;
}
需要修改什么?
Following parameters are given:
boolean a = true ;
boolean b = false ;
boolean c = true ;
I want to have minimal code of this version:
if ( ( a && ! b) || ( ! a && b) ) {
z1 += 99 ;
}
if (a ^ b) {
z1 += 19 ;
}
if ( ( a && b) || ( ! a && ! b) ) {
z1 += 118;
}
What needs to be modified?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个条件与第二个条件相同,第三个条件是其他条件的否定,所以我们
可以再次缩短它,无论 a 或 b 是什么,z1 都会增加 118,所以我们有
The first condition is the same as the second, the third is the negation of the others, so we have
We can shorten that again, whatever a or b is, z1 is augmented by 118, so we just have
如果您将来需要弄清楚这样的事情,那么您可能需要尝试编写一个表格(我认为它称为真值表,但这里一些更有数学头脑的人可能会纠正我)显示所有可能的输入及其各自的结果。编写完表格后,您应该能够快速识别总体逻辑并可能对其进行简化。
对于上面的表格可能如下所示;
浏览每一行并将 z1 的效果写在该列中。这应该可以让您轻松确定正在发生的事情以及如何缩短它(如果可能)。
If you need to figure out things like this in future then you might want to try writing a table (I think its called a truth table, but some of the more mathematically minded here may correct me) showing all possible inputs and their respective outcomes. Once you've written the table you should be able to quickly identify the overall logic and possibly simplify it.
For the above a table might look like this;
Go through each row and write the effects of z1 in the column. This should allow you to easily determine what's going on and how to shorten it, if possible.
你可以使用
你可以使用
就可以了
you can use
you can use
is ok in its place