Print the next smallest and next largest number that have the same number of 1 bits in their binary representation Given an integer , print the next smallest and next largest number that have the same number of 1 bits in their binary representation.

How can I improve this?

void printNextNumber(int num){
    int inputNumOfBits = calcBits(num);

    int  nextLargest = num + 1, nextSmallest = num - 1;

    //nextLargest
    while (true){
        if (calcBits(nextLargest) == inputNumOfBits){
            break;
        }
        nextLargest++;
    }

    //nextSmallest
    while (true){
        if (calcBits(nextSmallest) == inputNumOfBits){
            break;
        }
        nextSmallest--;
    }
    System.out.println("Next largest: " + nextLargest);
    System.out.println("Next smallest: " + nextSmallest);
}

private int calcBits(int x){
    int count = 0;
    int i = 0;

    while (i &lt; 32){
        if ((x &amp; (1&lt;&lt;i)) != 0){
            count++;
        }
        i++;
    }
    return count;
}
You are solving this the "mathematical" way.

what about the "lego" way?

Your number consists of a string with "1"s and "0"s.

[edit]
thanks to @graybeard who pointed that the method must be changed to fulfill the requirement:

The next bigger number is when you switch the position of the most right "0" that is followed by a "1" with that following "1".

int nextBigger(int number){
  char[] binaryDigits = BigIntger.valueOf(number).toString(2).toCharArray();
  int lastZeroFollowedByIndex = findLastZeroFollowedByOneIn(binaryDigits);
  binaryDigits[lastZeroFollowedByIndex]    = '1';     
  binaryDigits[lastZeroFollowedByIndex +1] = '0';
  return new BigInteger(new String(binaryDigits),2).intValue();
}