-
Notifications
You must be signed in to change notification settings - Fork 0
/
turns JAVA
41 lines (35 loc) · 1.11 KB
/
turns 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
package learning;
public class algorithms {
public static String FindsNIn(int N, int LOW, int HIGH) {
/*
complexity: O(log n)
--- binary search ---
returns how many turns are necessary to find the answer
calculates the number which to find from LOW to HIGH
:param N: the number to find
:param LOW: start number
:param HIGH: end number
:return: turns
*/
int turns = 0;
int mid;
while (HIGH >= LOW) {
turns ++;
mid = (HIGH + LOW) / 2;
System.out.printf("tern: %dth\n", turns);
System.out.printf("Let it be %d Although no! Let me think ...\n", mid);
if (mid < N) {
LOW = mid + 1;
} else if (mid > N) {
HIGH = mid - 1;
} else {
return String.format("Yes, that's right! I need for this %d turns", turns);
}
}
return "Sorry, I couldn't find anything :( ";
}
public static void main(String[] args) {
String terns = FindsNIn(16,1,20);
System.out.println(terns);
}
}