Problem Statement

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

Problem Link

Power of 2 - InterviewBit

Code

typedef long long int ll;
string mulBy2(string s)
{
    int n = s.size();
    int i = n-1;
    string res = "";
    int carry = 0;

    while(carry||i>=0)
    {
        int num = i>=0 ? s[i]-'0' : 0;

        int prod = num*2 + carry;

        int digit = prod%10;
        res+=(digit+'0');
       
        carry = prod/10;
        i--;
    }
    
    reverse(res.begin(),res.end());

    return res;
    
}
int Solution::power(string A) {
  
  string s = "1";
  int n = A.size();

  int last = A[n-1] - '0';
  if(last%2)
  return 0;
  while(1)
  {
      s = mulBy2(s);
      
      if(s==A)
      return 1;

      if(s.size()>A.size())
      return 0;
  }
  return 0;

}