c++ binary pow (log(n))


  • 1
    double myPow(double x, int n) {
      bool if_neg = false;
      long long lln = n;
      if (lln < 0) {
        lln *= -1;
        if_neg = true;
      }
      double ans = 1;
      while (lln) {
        if (lln % 2 == 1)
          ans *= x;
        x *= x;
        lln >>= 1;
      }
      if (if_neg) return 1 / ans;
      else return ans;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.