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 < 32){
if ((x & (1<<i)) != 0){
count++;
}
i++;
}
return count;
}
How can I improve this?
comment your code. Specify whether negative numbers are to be considered, and how those are represented. Describe the algorithm you use. Tell whether you are after better code for that algorithm, or a better algorithm. (next smallest/largest
? smaller/larger, preceding/succeeding?) \$\endgroup\$nextLargest
- there is only one largest. There cannot be a nextLargest. So this should better benextLarger
whilenextBigger
fits better to the context of numbers \$\endgroup\$//nextLargest while (){ if (){ break;
better put this in a separate method, where you can return from. the "separation comment" tells you that the following code should be places in a method of its own, and the comment content gives you the name of that method. \$\endgroup\$