Topic describes
Their thinking
- When n is odd or even, it is negative. When n is 0, it is negative.
- Case 1: (2,4) = (2,2) * (2,2)
- Case 2 :(2,5) = (2,2) * (2,2) * 2
- See the notes for details
The problem solving code
var myPow = function(x, n) {
/ /! N is odd and n is even
// (2,4) = (2,2) * (2,2)
// case 2 :(2,5) = (2,2) * (2,2) * 2
// First of all, n can be 0, positive or negative
if (n === 0) return 1;
// Either positive or negative numbers are converted to positive numbers first
const res = dfs(x,Math.abs(n));
if (n > 0) {
return res;
} else {
return 1/res;
}
function dfs(x,n) {
// End condition of recursion
if (n === 1) {
return x;
}
let temp = dfs(x,Math.floor(n/2));
return n % 2 ? (x * temp * temp) : (temp * temp)
}
}
Copy the code
Conclusion (this topic gives us the enlightenment of thinking)
- Learn to recurse and find patterns between exponents.