如何在不使用数学/按位运算符的情况下找到偶数/奇数?
Are you allowed to cheat by going to a simpler, rather than trickier, solution than the standard i % 2 == 0
? :) And secondarily, are you allowed to cheat by calling a JDK method which uses arithmetic or bitwise ops? If so, you could:
How about this:
int value = 7;
String message = String.format("Is %s odd or even?",value);
Object[] options = {"Odd","Even"};
int n = JOptionPane.showOptionDialog(null,
message,
"Is It Odd Or Even",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
System.out.println(String.format("%s is %s", value, options[n]));
The original question doesn't give the size of the data set.
This seems like a really weird arbitrary condition but what the heck. Just convert it to a string and check if the last character is a 0, 2, 4, 6, or 8.
I believe the answer is, you can't.
Any solution might consider will be composed of bitwise or mathematical operators. You can call or write a method which hides this from you, but it uses operators all the same.
you can do
public static boolean isOdd(int n) {
return (n << -1) < 0;
}
I can think of the following ways to check if a number is odd, listed in order of performance:
// Using bit-manipulation (fastest)
boolean odd = ((num & 1) == 1);
// Using remainder (fast, but division is slower than bit-manipulation)
boolean odd = ((num % 2) == 1);
// Using conversion to string (very slow, but doesn't use any operators)
boolean odd = Integer.toString(num, 2).endsWith("1");
Try below java code.
String[] sarr = {"Odd Number","Even Number"};
int num = 7;
int x = num%2;
System.out.println(sarr[x]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.