不使用比較運算就可以求出兩個數的最大值與最小值
public class MaxMinT {
//可能會溢位
public static int max(int a,int b){
return(a + b + Math.abs(a-b))/2;
}
public static int min(int a,int b){
return(a + b - Math.abs(a-b))/2;
}
//不會溢位
public static long max1(long a,long b){
return(a + b + Math.abs(a - b))/2;
}
public static long min1(long a,long b){
return(a+b-Math.abs(a-b))/2;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("max(3,5)=" + max(1234567890,500000));
System.out.println("max(3,5)=" + max(3,5));
System.out.println("max(3,5)=" + max1(3,5));
System.out.println("max(3,5)=" + max1(1234567890,1234567890));
}
}