3 numbers in ascending order WITHOUT the use of conditional statements in Java. As in I can't use if statements at all

前端 未结 6 1036
旧巷少年郎
旧巷少年郎 2021-01-25 00:24

My code looks like this so far:

public class ThreeSort {
    public static void main(String[] args) {

        int num1 = Integer.parseInt(args[0]);
        int          


        
6条回答
  •  被撕碎了的回忆
    2021-01-25 01:05

    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;
    

提交回复
热议问题