Skip to content

Latest commit

 

History

History
61 lines (43 loc) · 1.06 KB

File metadata and controls

61 lines (43 loc) · 1.06 KB

109. implement Math.pow()

Problem

https://bigfrontend.dev/problem/implement-Math-pow

Problem Description

Can you write your own Math.pow() ? The power would only be integers.

pow(1, 2);
// 1

pow(2, 10);
// 1024

pow(4, -1);
// 0.25

All inputs are safe.

Follow-up

You can easily solve this problem by multiplying the base one after another, but it is slow. For power of n, it is needed to do the multiplication n times, can you think of a faster solution ?

Solution

/**
 * @param {number} base
 * @param {number} power - integer
 * @return {number}
 */
function pow(base, power) {
  if (power < 0) {
    return 1 / _pow(base, -power);
  }

  return _pow(base, power);
}

function _pow(base, power) {
  if (power === 0) {
    return 1;
  }

  if (power === 1) {
    return base;
  }

  const halfResult = _pow(base, Math.floor(power / 2));
  const result = halfResult * halfResult;
  return power % 2 === 0 ? result : base * result;
}