-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-16 Power(x,n)
55 lines (49 loc) · 1.06 KB
/
Day-16 Power(x,n)
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
53
54
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
for (long i = 0; i < N; i++)
ans = ans * x;
return ans;
}
};
class Solution {
public double myPow(double x, long n) {
if(n < 0){
x = 1/x;
n = -n;
}
if(n == 0)
return 1;
if(n == 1)
return x;
double m = myPow(x,(int)(n/2));
m *= m;
if(n % 2 == 1){
m = m * x;
}
return m;
}
}
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double result = 1;
double currentResult = x;
for (long i = N; i > 0; i /= 2) {
if ((i % 2) == 1) {
result = result * currentResult;
}
currentResult = currentResult * currentResult;
}
return result;
}
}