Using bit manipulation


#1

https://www.hackerearth.com/practice/notes/bit-manipulation/ —>check it out for more details.

I’m using BigInteger here to handle large string value

 import java.math.BigInteger;    
 public class Solution {
public int power(String A) {
    
    //https://www.hackerearth.com/practice/notes/bit-manipulation/
    
    //Properties for numbers which are powers of 2, is that they have one
    //and only one bit set in their binary representation. 
    //If the number is neither zero nor a power of two,
    //it will have 1 in more than one place.
    //So if x is a power of 2 then x & (x-1) will be 0.
    BigInteger x = new BigInteger(A);
      if(x.equals(BigInteger.ZERO) || x.equals(BigInteger.ONE))
    return 0;
      else
     {
    while((x.remainder(BigInteger.valueOf(2))).equals(BigInteger.ZERO))
    x = x.divide(BigInteger.valueOf(2));
    if (x.equals(BigInteger.ONE))return 1;else return 0;
    }
    
     }
    }