-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathPrintBinary.java
37 lines (32 loc) · 1.36 KB
/
PrintBinary.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
package ds.recursion;
public class PrintBinary {
public static void printBinary(int n) {
// base case
if (n < 2) {
System.out.print(n);
} else { // recursive case
// this is similar to stack.push(n / 2);
printBinary(n / 2);
// this method waits until printBinary(n / 2) gets done
// this is similar to invoke stack.pop(n);
printBinary(n % 2);
}
}
/*
how it works
let's say n = 8
n = 8 else condition works
n = 4 else condition works
n = 2 else condition works
n = 1 else condition works
coming to this step base case works and then algorithm goes up again
n = 1 if condition works, just prints value 1
n = 2 else condition printBinary(n % 2) method works, it calls method itself with value 2 % 2 = 0
and once method has been called it reaches base and just prints value 0;
n = 4 else condition printBinary(n % 2) method works, it calls method itself with value 4 % 2 = 0
and once method has been called it reaches base and just prints value 0;
n = 8 else condition printBinary(n % 2) method works, it calls method itself with value 8 % 2 = 0
and once method has been called it reaches base and just prints value 0;
Finally we have got 1000 result
*/
}