File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /* Approach
2+
3+ We use exponentiation by squaring to efficiently compute x^n:
4+
5+ Handle base cases:
6+
7+ If n == 0, return 1.
8+ If x == 0, return 0 (unless n is 0).
9+ Handle negative powers:
10+
11+ If n < 0, compute x^{-n} by inverting x (x = 1/x) and making n positive.
12+ For positive powers:
13+
14+ If n is even: x^n = (x^(n/2)) * (x^(n/2))
15+ If n is odd: x^n = x * (x^(n-1))
16+ Implement iteratively to avoid recursion stack overflow for large n:
17+
18+ While n > 0:
19+ If n is odd, multiply result by x.
20+ Square x and divide n by 2.
21+ Return the accumulated result. */
22+
23+ class Solution {
24+ public:
25+ double myPow (double x, int n) {
26+ long long N = n; // Convert to long long to handle INT_MIN
27+ if (N < 0 ) { // Handle negative powers
28+ x = 1 / x;
29+ N = -N;
30+ }
31+
32+ double result = 1.0 ;
33+ while (N > 0 ) {
34+ if (N % 2 == 1 ) { // If the current power is odd
35+ result *= x;
36+ }
37+ x *= x; // Square x
38+ N /= 2 ; // Divide n by 2
39+ }
40+
41+ return result;
42+ }
43+ };
44+
You can’t perform that action at this time.
0 commit comments