-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindNumZeros.java
More file actions
46 lines (41 loc) · 1.14 KB
/
Copy pathFindNumZeros.java
File metadata and controls
46 lines (41 loc) · 1.14 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
package pkg;
public class FindNumZeros {
public static void main(String[] args) {
int[] array = { 0, 1, 1, 1, 1, 1 };
System.out.println(findNumZeros(array, 0, array.length - 1));
System.out.println(findNumZerosRecursive(array, 0));
System.out.println(findNumZerosRecursive2(array, 0, array.length - 1));
}
private static int findNumZeros(int[] input, int start, int end) {
int count = 0;
int mid = 0;
while (start <= end) {
mid = end - start / 2;
if (input[mid] == 0) {
count += mid + 1;
start = mid + 1;
} else {
end = mid - 1;
}
}
return count;
}
private static int findNumZerosRecursive(int[] input, int startIndex) {
int count = 0;
if (startIndex < input.length - 1 && input[startIndex] == 0) {
count = 1 + findNumZerosRecursive(input, startIndex + 1);
}
return count;
}
private static int findNumZerosRecursive2(int[] input, int start, int end) {
int count = 0;
int mid = end - start / 2;
if (start <= end) {
if (input[mid] == 0)
count = mid + 1 + findNumZerosRecursive2(input, mid + 1, end);
else
count = findNumZerosRecursive2(input, start, mid - 1);
}
return count;
}
}