在不使用条件代码的情况下确定数字是奇数还是偶数 [英] Determine whether number is odd or even without using conditional code

查看:53
本文介绍了在不使用条件代码的情况下确定数字是奇数还是偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用Java中的 if 条件或三元运算符的情况下查找数字是奇数还是偶数?

How to find whether a number is odd or even, without using if condition or ternary operators in Java?

这个问题是由我的老师提出的.他还给我一个暗示,可以通过使用按位运算符来实现.

This question is given by my teacher. He also give me a hint that it is possible by using a bitwise operator.

推荐答案

很少有不使用 if 并获得与 if 相同的行为的方法.像三元运算符 condition一样使用?valueIfTrue:valueIfFalse switch/case .

There are few ways to not use if and get behavior that will be same as if if was used, like ternary operator condition ? valueIfTrue : valueIfFalse or switch/case.

但是要棘手的是,您也可以使用数组,并尝试将我们的值进行转换到正确的数组索引.在这种情况下,您的代码可能看起来像

But to be tricky you can also use arrays and try to figure some transformation of our value to proper array index. In this case your code could look like

int number = 13;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);

输出:

13 is odd


您可以使用 number&更改 number%2 .1 使用您老师的建议.可以在此处找到其工作方式的说明.


You can change number % 2 with number & 1 to use suggestion of your teacher. Explanation of how it works can be found here.

这篇关于在不使用条件代码的情况下确定数字是奇数还是偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆