Basic and easy to understand C++ solution with comments


#1

I tried to make the code as explanatory as possible if need any changes let me know!
Thanks.
// Binary representation of any power of 2 will have only one 1
// We keep dividing the number and check the remainder
// if remainder == 1 and return false;
// and remainder == 0 and quotient == 1 that mean we have exhausted the number return true
// else keep going by changing the divident to quotient.
// make sure you remove the un-necessary front zeros

void removeFrontZeros(string &s) {
  int i = 0;
  int n = s.length();
  while (i < n && s[i] == '0') {
    i++;
  }

  s =  s.substr(i, n - i);
}

int Solution::power(string s) {
  removeFrontZeros(s);
  string dividend = s;
  string quotient = "";
  int rem = 0;

  int n = 0;
  int i = 0;
  int base = 0;
  while (1) {
    quotient = "";
    n = dividend.length();
    i = 0;
    rem = 0;
    while (i < n) {
      base = (rem * 10 + (dividend[i] - '0')) / 2;
      quotient.push_back(base + '0');
      rem = (rem * 10 + (dividend[i] - '0')) % 2;
      i++;
    }
    if(rem == 0 && quotient.length() == 1 && quotient[0] == '1' ) {
      return true;
    } else if (rem == 1) {
      return false;
    }
    removeFrontZeros(quotient);
    dividend = quotient;
  }
}

#2

Good Code :grinning: