Saturday, October 20, 2012

Mathematics2

Q2. How to find if a number is power of 2?
Answer:
* Binary representation of a number which is power of 2 will have only 1 bit on.
* See below some 4 bits representation of numbers
    1 = 0001
    2 = 0010
    4 = 0100
* We need to check the binary representation of the number will contain only 1 bit on.

public class Mathematics2 {
    public static boolean isPowerOfTwo(int number) {
        if((number & (number - 1)) == 0 ){
            return true;
        }
        return false;
    }
  
    public static void main (String[] args) {
        System.out.println(isPowerOfTwo(1));
        System.out.println(isPowerOfTwo(2));
        System.out.println(isPowerOfTwo(16));
        System.out.println(isPowerOfTwo(18));
    }
}

No comments:

Post a Comment

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