is Power Of Two - Java java.lang

Java examples for java.lang:Math Calculation

Description

is Power Of Two

Demo Code


//package com.java2s;
import java.math.BigInteger;

public class Main {
    public static boolean isPowerOfTwo(int intValue) {
        if (intValue == 0) {
            return false;
        }/*from w  w w. j  ava2s .com*/

        while ((intValue & 1) == 0) {
            intValue = intValue >>> 1;
        }

        return intValue == 1;
    }

    public static boolean isPowerOfTwo(long longValue) {
        if (longValue == 0L) {
            return false;
        }

        while ((longValue & 1L) == 0L) {
            longValue = longValue >>> 1;
        }

        return longValue == 1L;
    }

    public static boolean isPowerOfTwo(BigInteger bintValue) {
        if (bintValue == null) {
            return false;
        }

        int bitIndex = bintValue.getLowestSetBit();

        if (bitIndex < 0) {
            return false;
        }

        return bintValue.clearBit(bitIndex).equals(BigInteger.ZERO);
    }
}

Related Tutorials