-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec_11.cpp
52 lines (42 loc) Β· 1.06 KB
/
lec_11.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public:
double myPow(double x, int n) {
double ans = 1.0;
bool isNegative = (n < 0); // Check if exponent is negative
long long N = abs((long long)n); // Convert to positive to avoid overflow
for (long long i = 0; i < N; i++) {
ans = ans * x;
}
if (isNegative) {
return 1.0 / ans;
}
return ans;
}
};
// alternative solution
class Solution {
public:
double myPow(double x, int n) {
double ans = 1.0;
double oriNum = n;
if( x == 0 || x == 1){
return x;
}
if(n<0){
x = 1/x;
n = -(n +1);
ans = ans*x;
}
while(n>0){
if(n%2==1){
ans = ans*x;
n = n-1;
}
else{
n = n/2;
x = x*x;
}
}
return ans;
}
};