Skip to content

Commit 7a1f442

Browse files
committed
feat: Add NextHigherSameBitCount new algorithm with Junit tests
1 parent 2a518e3 commit 7a1f442

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* This class provides a method to find the next higher number
5+
* with the same number of set bits as the given number.
6+
*
7+
* @author Hardvan
8+
*/
9+
public final class NextHigherSameBitCount {
10+
private NextHigherSameBitCount() {
11+
}
12+
13+
/**
14+
* Finds the next higher integer with the same number of set bits.
15+
*
16+
* @param n the input number
17+
* @return the next higher integer with the same set bit count
18+
*/
19+
public static int nextHigherSameBitCount(int n) {
20+
int c = n & -n;
21+
int r = n + c;
22+
return (((r ^ n) >> 2) / c) | r;
23+
}
24+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.params.ParameterizedTest;
6+
import org.junit.jupiter.params.provider.CsvSource;
7+
8+
class NextHigherSameBitCountTest {
9+
10+
@ParameterizedTest
11+
@CsvSource({
12+
"5, 6", // 101 -> 110
13+
"7, 11", // 0111 -> 1011
14+
"3, 5", // 011 -> 101
15+
"12, 17", // 001100 -> 010001
16+
"15, 23" // 01111 -> 10111
17+
})
18+
void
19+
testNextHigherSameBitCount(int input, int expected) {
20+
assertEquals(expected, NextHigherSameBitCount.nextHigherSameBitCount(input));
21+
}
22+
}

0 commit comments

Comments
 (0)