LeetCode/pow-x-n/nodejs/index.js

97 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [231, 231 1]
*/
const { assert } = require('../../util/js');
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
const isNeg = n < 0 ? true: false;
if (n === 0) {
return 1;
}
if (n === 1) {
return x;
}
if (n === -1) {
return 1/x;
}
const storedCalcs = {};
const recursivePow = (x, n) => {
if (n === 2) {
return isNeg ? (1/x * 1/x) : x * x;
}
if (n === 1) {
return isNeg ? 1/x : x;
}
if (n === 0) {
return 1;
}
const firstHalf = Math.floor(parseInt(Math.abs(n) / 2));
const secondHalf = Math.abs(n) - firstHalf;
if(storedCalcs[n]) {
return storedCalcs[n];
}
const result = recursivePow(x, firstHalf) * recursivePow(x, secondHalf);
storedCalcs[n] = result;
return result;
};
return recursivePow(x, n);
}
/* Test Case 1
* Input: 2.00000, 10
* Output: 1024.00000
*/
x = 2.00000;
n = 10;
sol = 1024.00000;
assert(myPow(x, n) == sol, 'Output: 1024.00000');
/* Test Case 2
* Input: 2.10000, 3
* Output: 9.261
*/
x = 2.10000;
n = 3;
sol = 9.261;
assert(myPow(x, n).toFixed(3) == sol, 'Output: 9.261');
/* Test Case 3
* Input: 2.00000, -2
* Output: 0.25
*/
x = 2.00000;
n = -2;
sol = 0.25;
assert(myPow(x, n) == sol, 'Output: 0.25000');