Pow(x, n)

Implement pow(x, n).

def myPow(_x: Double, _n: Int): Double = {
  var (x, n) = (_x, _n)
  if (x == 0) 0
  if (n == 0) 1
  else {
    if (n < 0) {
      x = 1 / x
      n = -n
    }
    var pow = 1
    while (n > 0) {
      if ((n & 1) == 1) {
        pow *= x
      }
      x *= x
      n <<= 1
    }
    pow
  }
}

Last updated