Sunday, October 21, 2012

BitManipulation3

Q3. Write a method to find the maximum of two numbers without using if-else or any other comparison operator.

Answer:

public class BitManipulation3 {

    public static int maximum(int a, int b) {
        int c = a - b;
        int k = (c >> 15) & 1;
        return a - k * c;
    }

    public static void main(String[] args) {
        System.out.println(maximum(5, 10));
        System.out.println(maximum(25, 10));
        System.out.println(maximum(-25, 10));
        System.out.println(maximum(-25, -10));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.