This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
The task is to replicate the Math.pow() function, with the powers only integers.
The boilerplate code
function pow(base, power){
// your code here
}
If the power is 0, return 1
if (power === 0) return 1
Multiply the base by the absolute value of the power, taking negative powers into consideration
let result = 1;
let absPower = Math.abs(power);
for (let i = 0; i < absPower; i++) {
result *= base;
}
If the power is negative, return the reciporcal. Otherwise, return the result
return power > 0 ? result : 1 / result;
The final code
function pow(base, power){
// your code here
if(power === 0) return 1;
let result = 1;
let absPower = Math.abs(power);
for(let i = 0; i < absPower; i++) {
result *= base;
}
return power > 0 ? result : 1 / result;
}
That's all folks!
This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
Bukunmi Odugbesan | Sciencx (2025-11-24T22:13:05+00:00) Coding Challenge Practice – Question 65. Retrieved from https://www.scien.cx/2025/11/24/coding-challenge-practice-question-65/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.