Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation
Analysis:
Assume that we are given 11010100110, if we want to find out the next larger number, we can
1. from right to left, find out the first '1'. (11010100110)
2. after the first '1', find out the first '0'. (11010100110)
3. change this '0' to '1'. (11010101110)
4. change the '1' next to current digit to '0', equal to switch these 2 digits. (11010101010)
5. move all the passed '1' (according to the requirement "the same number of 1 bits") to right most in order to find out the "next largest". (11010101001)
Similarly, for the next smallest number of 11010100110
1. find out the 1st '0'. (11010100110)
2. after the first '0', find the first '1'. (11010100110)
3. change this '1' to 0. (11010100100)
4 change the next to current digit to '1', equal to switch these 2 digits. (11010100101)
5. move all the passed '1' to left most in order to find out the "next smallest". (in this case, no '1' digit passed)
public class Answer {
public static int nextNumber(int num){
// find the 1st '1'
int index = 0;
int countOne = 0;
while(!(((1<<index) & num)>0)) index++;
// turn on next 0
while(((1<<index)&num)>0) {
index++;
countOne++;
}
num = num|(1<<index);
// turn off the next 1
index--;
num = ~(1<<index)&num
countOne--;
// move remaining 1 to right most
// set 1
for(int i=0; i<countOne; i++){
num = (1<<i)|num;
}
// set 0
for(int i=countOne; i<index; i++){
num = ~(1<<i)&num
}
return num;
}
public static int prevNumber(int num){
// find the 1st 0
int index = 0;
int countOne = 0;
while(((1<<index)&num)>0) {
index++;
countOne++;
}
// turn off next 1
while(!(((1<<index)&num)>0)) index++;
num = ~(1<<index)&num
// turn next digit to 1
index--;
num = (1<<index)|num;
// move passed 1s to left most
for(int i=index-1; i>=index-countOne;i--) num = (1<<i)|num; // set 1
for(int i=0; i<index-countOne; i++) num = ~(1<<i)&num // set 0
return num;
}
public static void main(String[] args) {
int a = 27;
System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a));
int b = nextNumber(a);
System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b));
int c = prevNumber(a);
System.out.println(c + ": " + AssortedMethods.toFullBinaryString(c));
}
Note: set 1 at n digit, use (1<<n)|num; set 0 at n digit, use ~(1<<n)&num.