silver-hands / sss

0 stars 0 forks source link

【Q101】面试题16. 数值的整数次方 #101

Open fly0o0 opened 4 years ago

fly0o0 commented 4 years ago

面试题16. 数值的整数次方

fly0o0 commented 4 years ago
/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
  if (x == 0) {
    return 0
  }

  if (n < 0) {
    x = 1 / x
    n = -n
  }

  let res = 1

  while (n > 0) {
    // n % 2 == 1
    if (n & 1) {
      res *= x
    }
    // x = x ^ 2
    x *= x
    // n >>> 1
    n /= 2
  }

  return res
};