[BAEL-3405] Solving Binary Gap using Recursion (#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
This commit is contained in:
parent
e910017c43
commit
2ba43cfc27
@ -0,0 +1,17 @@
|
||||
package com.baeldung.algorithms.binarygap;
|
||||
|
||||
public class BinaryGap {
|
||||
static int calculateBinaryGap(int n) {
|
||||
return calculateBinaryGap(n >>> Integer.numberOfTrailingZeros(n), 0, 0);
|
||||
}
|
||||
|
||||
static int calculateBinaryGap(int n, int current, int maximum) {
|
||||
if (n == 0) {
|
||||
return maximum;
|
||||
} else if ((n & 1) == 0) {
|
||||
return calculateBinaryGap(n >>> 1, current + 1, maximum);
|
||||
} else {
|
||||
return calculateBinaryGap(n >>> 1, 0, Math.max(maximum, current));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.binarygap;
|
||||
|
||||
import static com.baeldung.algorithms.binarygap.BinaryGap.calculateBinaryGap;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BinaryGapUnitTest {
|
||||
|
||||
@Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
|
||||
|
||||
int result = calculateBinaryGap(63);
|
||||
assertEquals(0, result);
|
||||
}
|
||||
|
||||
@Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
|
||||
|
||||
int result = calculateBinaryGap(40);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
|
||||
|
||||
int result = calculateBinaryGap(9);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
|
||||
|
||||
int result = calculateBinaryGap(145);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user