-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXPowerNOptimized.java
More file actions
60 lines (44 loc) · 1.11 KB
/
Copy pathXPowerNOptimized.java
File metadata and controls
60 lines (44 loc) · 1.11 KB
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
55
56
57
58
59
60
package recursion.part1;
public class XPowerNOptimized {
public static int pow(int x, int n) {
if (n == 0) {
return 1;
}
int halfPow = pow(x, n/2);
int halfPowSquare = halfPow * halfPow;
// n is odd
if (n % 2 != 0) {
halfPowSquare *= x;
}
return halfPowSquare;
}
public static void main(String[] args) {
int x = 2, n = 10;
System.out.println(pow(x, n));
}
}
// print x^n (optimized)
/*
Pow(x, n) (LeetCode 50)
https://leetcode.com/problems/powx-n/description/
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
return 1 / helper(x, -N);
}
return helper(x, N);
}
private double helper(double x, long n) {
if (n == 0) {
return 1;
}
double halfPow = helper(x, n / 2);
double halfPowSquare = halfPow * halfPow;
if (n % 2 != 0) {
halfPowSquare *= x;
}
return halfPowSquare;
}
}
*/