MEDIUM NC#141 Math & Geometry
50. Pow(x, n)
๐ Problem
Implement pow(x, n), which calculates x raised to the power n.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Handle negative n by converting to positive and using 1/x
- โ Use iterative approach: x^15 * x^14 * x^13 * ...
- โ Or use binary exponentiation for O(log n) time
- โ Time: O(log n), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขHandle negative n by converting to positive and using 1/x
- โขUse iterative approach: x^15 * x^14 * x^13 * ...
- โขOr use binary exponentiation for O(log n) time
Common Pitfalls
- โขTime: O(log n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
myPow(2, 10); Expected:
2147483648 Test Case 2
Not run Input:
myPow(2.1, 3); Expected:
9.261000000000001 Test Case 3
Not run Input:
myPow(2, -2); Expected:
0.5 ๐ Code Editor
๐ค Output