java按升序排列数字,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));

Also as the operator ^ denotes bitwise xor. so another way is:

mid=num1^num2^num3^max^min;

EXAMPLE:

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;

}

OUTPUT: 10.

Also as OldCurmudgeon said below you can calculate the mid with below formula:

int mid = num1 + num2 + num3 - min - max;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值