-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathIntDivider.java
52 lines (42 loc) · 1.29 KB
/
IntDivider.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
50
51
52
package by.andd3dfx.numeric;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Реализовать вручную функцию целочисленного деления int divide(int a, int b)
*
* @see <a href="https://youtu.be/jhKuxPDCa54">Video solution</a>
*/
public class IntDivider {
public static int divide(int a, int b) {
if (b == 1) {
return a;
}
var counter = 0;
while (a >= b) {
a -= b;
counter++;
}
return counter;
}
public static int divideOptimized(int a, int b) {
int remains = a;
int counter = 0;
int power = 1;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(power);
int iterationsAmount = 0;
while (remains >= b) {
if (remains >= power * b) {
remains -= power * b;
counter += power;
stack.push(power);
power *= 2;
} else {
power = stack.pop();
}
iterationsAmount++;
}
System.out.println(String.format("Division: %d/%d=%d. Iterations performed: %d", a, b, counter, iterationsAmount));
return counter;
}
}