在不使用条件代码的情况下确定数字是奇数还是偶数
如何在不使用Java中的条件或三元运算符的情况下查找数字是奇数还是偶数?
这个问题是我的老师给出的。 他还给我一个暗示,通过使用按位运算符是可能的。
有几种方法可以不使用if
并获得与使用if
相同的行为,如三元运算符condition ? valueIfTrue : valueIfFalse
condition ? valueIfTrue : valueIfFalse
或switch/case
。
但是要棘手,你也可以使用数组并尝试将我们的值转换为正确的数组索引。 在这种情况下,您的代码可能看起来像
int number = 13; String[] trick = { "even", "odd" }; System.out.println(number + " is " + trick[number % 2]);
输出:
13 is odd
您可以使用number & 1
更改number % 2
以使用教师的建议。 可在此处找到有关其工作原理的说明。
考虑二进制格式的数字表示(例如,5将是0b101)。 奇数的单数为“1”,偶数为零。 所以你要做的就是按位 – 并且只用1来提取那个数字,并检查结果:
public static boolean isEven (int num) { return (num & 1) == 0; }
int isOdd = (number & 1);
如果number为奇数,则isOdd
为1
,否则为0
。
你的意思是这样的吗?
boolean isEven(int value) { return value % 2 == 0; } boolean isOdd(int value) { return value % 2 == 1; }
每个奇数在其二进制表示的末尾都有1。
样品:
public static boolean isEven(int num) { return (num & 1) == 0; }
刚看到'Without using IF'
boolean isEven(double num) { return (num % 2 == 0) }
只是快速包装已定义的流程…
public String OddEven(int n){ String oe[] = new String[]{"even","odd"}; return oe[n & 1]; }
我会用:
( (x%2)==0 ? return "x is even" : return "x is odd");
一行代码。
# /* **this program find number is odd or even without using if-else, ## switch-case, neither any java library function...*/ ##//find odd and even number without using any condition class OddEven { public static void main(String[] args) { int number = 14; String[] trick = { "even", "odd" }; System.out.println(number + " is " + trick[number % 2]); } } /**************OUTPUT************* // 14 is even // ................... //13 is odd
方法1:
System.out.println(new String[]{"even","odd"}[Math.abs(n%2)]);
方法2:
System.out.println(new String[]{"odd","even"}[(n|1)-n]);
方法1与接受的答案的不同之处在于它也考虑了负数,这也被认为是偶数/奇数。
import java.util.Scanner; public class EvenOddExample { public static void main(String[] args) { System.out.println("\nEnter any Number To check Even or Odd"); Scanner sc=new Scanner(System.in); int no=sc.nextInt(); int no1=no; while (no>1) { no=no-2; } if(no==0) { System.out.println(no1 +" is evenNumber"); } else { System.out.println(no1 +" is odd Number"); } } }
你也可以使用按位移位运算符(数字>> 1)<< 1 ==数字然后甚至奇数
嗯,是的,你可以使用按位运算符。 这是一个例子,
public class EvenOddBitwise { public static void main(String[] args) { int number = 64; if((number & 1) == 1) { System.out.println(number + " is Odd."); } else { System.out.println(number + " is Even."); } } }