Pow(x, n): the idea to remember.
Compute a floating point base raised to a signed integer exponent, assuming a valid finite result.
The core insight
Repeatedly square the base and consume exponent bits; invert the base for a negative exponent.
Why it works
Each exponent bit selects one power of two factor, reconstructing the exponent with logarithmically many multiplications.
The mistake to avoid
Widen the exponent before negating Integer.MIN_VALUE. Zero to a negative power is outside the valid input assumptions.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
double myPow(double x, int n) {
long power = n; // Widen before negating Integer.MIN_VALUE.
if (power < 0) { x = 1.0 / x; power = -power; }
double result = 1.0;
while (power != 0) {
if ((power & 1) != 0) result *= x;
x *= x;
power >>= 1;
}
return result;
}
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.