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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit