3个数字按升序排列,不使用Java中的条件语句。因为我根本不能使用if语句 [英] 3 numbers in ascending order WITHOUT the use of conditional statements in Java. As in I can't use if statements at all
本文介绍了3个数字按升序排列,不使用Java中的条件语句。因为我根本不能使用if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我的代码看起来像这样:
My code looks like this so far:
public class ThreeSort {
public static void main(String[] args) {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int num3 = Integer.parseInt(args[2]);
int x = Math.min(num1, num2);
int min = Math.min(x,num3);
int z = Math.max(num1, num2);
int max = Math.max(z, num3);
int a = 0;
int mid = 0;
while (mid >= min && mid <= max) {
mid = a;
}
System.out.println(min);
System.out.println(a);
System.out.println(max);
}
我知道如何做最小和最大但我遇到中间问题。知道怎么做没有条件语句吗?
I know how to do the min and the max but I'm having troubles with the middle one. Any idea how to do that without conditional statements?
推荐答案
在这种情况下有一个简单的算法:
in this case there is a simple algorithm for it:
mid = Math.max(Math.min(num1,num2), Math.min(Math.max(num1,num2),num3));
同样作为运营商 ^
表示按位 xor
。所以另一种方式是:
Also as the operator ^
denotes bitwise xor
. so another way is:
mid = num1 ^ num2 ^ num3 ^ max ^ min;
示例:
public static void main(String[] args) {
System.out.println(mid(70, 3, 10));
}
static int mid(int a, int b, int c) {
int mx = Math.max(Math.max(a, b), c);
int mn = Math.min(Math.min(a, b), c);
int md = a ^ b ^ c ^ mx ^ mn;
return md;
}
输出 10。
如同OldCurmudgeon所说 ,你可以计算出 mid
,其公式如下:
Also as OldCurmudgeon said below you can calculate the mid
with below formula:
int mid = num1 + num2 + num3 - min - max;
这篇关于3个数字按升序排列,不使用Java中的条件语句。因为我根本不能使用if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文