Power of 2

Find if Given number is power of 2 or not. More specifically, find if given number can be expressed as 2^k where k >= 1.

Input:

number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range)

Output:

return 1 if the number is a power of 2 else return 0

Example:

Input : 128
Output : 1
import java.math.BigInteger;

public class Solution {
    public int power(String A) {
        if (A.length() <= 1 && A.charAt(0) == '1')
            return 0;
        BigInteger n = new BigInteger(A);
        BigInteger one = BigInteger.valueOf(1);
        BigInteger nMinus1 = n.subtract(one);
        BigInteger ans = n.and(nMinus1);
        if (ans.equals(BigInteger.ZERO))
            return 1;
        return 0;
    }
}

Last updated