Java - Tìm số lớn nhất của 2 số không sử dụng bất kỳ một phép toán so sánh nào (Find the max of two numbers without using any of the comparison operators).






Lang thang thấy một thuật toán tìm số lớn nhất của 2 số nhưng không sử dụng bất kỳ một phép toán so sánh nào, thấy hay nên lưu lại chia sẻ với các bạn. ^^!








FindMaxOfTwoNumbersWithoutComparisonOperators.java
/**
 * @(#)FindMaxOfTwoNumbersWithoutComparisonOperators.java
 *
 * FindMaxOfTwoNumbersWithoutComparisonOperators application
 *
 * @author BUI NGOC SON
 * @version 1.00 2013/12/8
 */

public class FindMaxOfTwoNumbersWithoutComparisonOperators {
   
    public static void main(String[] args) {
       
        // TODO, add your application code
        int num_max = findMax(450,250);
        System.out.println("Max number: " + num_max);
       
       
    }
   
    private static int findMax( int x, int y)
    {
       int z = x - y;
       int i  = (z  >>  31)  &  0x1;
       int  max  =  x - i  *  z;
       return max;
    }
}

Source: programmerinterview.com

Sau khi chạy chương trình bạn sẽ được kết quả như hình bên dưới.











No comments:

Post a Comment