forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
49 lines (35 loc) · 981 Bytes
/
Main.java
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
public class Main {
// binarySearch
private static int binarySearch(Comparable[] arr, int l, int r, int target){
if(l > r)
return -1;
int mid = l + (r - l) / 2;
if(arr[mid].compareTo(target) == 0)
return mid;
else if(arr[mid].compareTo(target) > 0)
return binarySearch(arr, l, mid - 1, target);
else
return binarySearch(arr, mid + 1, r, target);
}
// sum
private static int sum(int n){
assert n >= 0;
if(n == 0)
return 0;
return n + sum(n - 1);
}
// pow2
private static double pow(double x, int n){
assert n >= 0;
if(n == 0)
return 1.0;
double t = pow(x, n / 2);
if(n % 2 == 1)
return x * t * t;
return t * t;
}
public static void main(String[] args) {
System.out.println(sum(100));
System.out.println(pow(2, 10));
}
}