File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments