Skip to content

Commit fdbadf9

Browse files
nnnkpmaibin
authored andcommitted
[BAEL-3405] Solving Binary Gap using Recursion (eugenp#8144)
* A quick and practical example of Hexagonal Architecture in Java * updated code as per eclipse formatter * [BAEL-3405] Solving Binary Gap using Recursion * removed java-hexagonal package
1 parent 6c06682 commit fdbadf9

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.algorithms.binarygap;
2+
3+
public class BinaryGap {
4+
static int calculateBinaryGap(int n) {
5+
return calculateBinaryGap(n >>> Integer.numberOfTrailingZeros(n), 0, 0);
6+
}
7+
8+
static int calculateBinaryGap(int n, int current, int maximum) {
9+
if (n == 0) {
10+
return maximum;
11+
} else if ((n & 1) == 0) {
12+
return calculateBinaryGap(n >>> 1, current + 1, maximum);
13+
} else {
14+
return calculateBinaryGap(n >>> 1, 0, Math.max(maximum, current));
15+
}
16+
}
17+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.algorithms.binarygap;
2+
3+
import static com.baeldung.algorithms.binarygap.BinaryGap.calculateBinaryGap;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
public class BinaryGapUnitTest {
9+
10+
@Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
11+
12+
int result = calculateBinaryGap(63);
13+
assertEquals(0, result);
14+
}
15+
16+
@Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
17+
18+
int result = calculateBinaryGap(40);
19+
assertEquals(1, result);
20+
}
21+
22+
@Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
23+
24+
int result = calculateBinaryGap(9);
25+
assertEquals(2, result);
26+
}
27+
28+
@Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
29+
30+
int result = calculateBinaryGap(145);
31+
assertEquals(3, result);
32+
}
33+
34+
}

0 commit comments

Comments
 (0)