- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathNextHigherSameBitCount.java
30 lines (28 loc) · 992 Bytes
/
NextHigherSameBitCount.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
packagecom.thealgorithms.bitmanipulation;
/**
* This class provides a method to find the next higher number
* with the same number of set bits as the given number.
*
* @author Hardvan
*/
publicfinalclassNextHigherSameBitCount {
privateNextHigherSameBitCount() {
}
/**
* Finds the next higher integer with the same number of set bits.
* Steps:
* 1. Find {@code c}, the rightmost set bit of {@code n}.
* 2. Find {@code r}, the rightmost set bit of {@code n + c}.
* 3. Swap the bits of {@code r} and {@code n} to the right of {@code c}.
* 4. Shift the bits of {@code r} and {@code n} to the right of {@code c} to the rightmost.
* 5. Combine the results of steps 3 and 4.
*
* @param n the input number
* @return the next higher integer with the same set bit count
*/
publicstaticintnextHigherSameBitCount(intn) {
intc = n & -n;
intr = n + c;
return (((r ^ n) >> 2) / c) | r;
}
}