最少的代码,缩短表达

发布于 2024-09-28 20:37:02 字数 332 浏览 3 评论 0原文

给出以下参数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

药祭#氼 2024-10-05 20:37:02

第一个条件与第二个条件相同,第三个条件是其他条件的否定,所以我们

if (a ^ b) {
   z1 += 99 + 19  // = 118
} else {
   z1 += 118
}

可以再次缩短它,无论 a 或 b 是什么,z1 都会增加 118,所以我们有

z1 += 118

The first condition is the same as the second, the third is the negation of the others, so we have

if (a ^ b) {
   z1 += 99 + 19  // = 118
} else {
   z1 += 118
}

We can shorten that again, whatever a or b is, z1 is augmented by 118, so we just have

z1 += 118
晨光如昨 2024-10-05 20:37:02

如果您将来需要弄清楚这样的事情,那么您可能需要尝试编写一个表格(我认为它称为真值表,但这里一些更有数学头脑的人可能会纠正我)显示所有可能的输入及其各自的结果。编写完表格后,您应该能够快速识别总体逻辑并可能对其进行简化。

对于上面的表格可能如下所示;

  a  |  b  |  z1
------------------
  t  |  t  |
  t  |  f  |
  f  |  t  |
  f  |  f  |

浏览每一行并将 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;

  a  |  b  |  z1
------------------
  t  |  t  |
  t  |  f  |
  f  |  t  |
  f  |  f  |

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.

吃兔兔 2024-10-05 20:37:02
if ( ( a && ! b) || ( ! a && b) ) {
}  

你可以使用

if ( a!=b) {
} 

if ( ( a && b) || ( ! a && ! b) ) {}  

你可以使用

if(a==b){}  

if (a ^ b) {}   

就可以了

if ( ( a && ! b) || ( ! a && b) ) {
}  

you can use

if ( a!=b) {
} 

if ( ( a && b) || ( ! a && ! b) ) {}  

you can use

if(a==b){}  

if (a ^ b) {}   

is ok in its place

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文