previous Power Of 2 - Java java.lang

Java examples for java.lang:Math Calculation

Description

previous Power Of 2

Demo Code



public class Main{
    public static int prevPowerOf2(int n) {
        if (!MathUtil.isPowerOf2(n)) {
            n = MathUtil.nextPowerOf2(n) / 2;
        }//  ww w.jav a  2s  .  c  o  m

        return n;
    }
    public static boolean isPowerOf2(int n) {
        boolean isPowerOf2;
        if (n <= 0 || (n - 1 & n) != 0) {
            isPowerOf2 = false;
        } else {
            isPowerOf2 = true;
        }

        return isPowerOf2;
    }
    public static int nextPowerOf2(int n) {
        --n;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        return (n | n >>> 16) + 1;
    }
}

Related Tutorials