Our senior developer gave us (trainees/jr. developers) a small exercise and that is to make our own Integer.toBinaryString(int n)
implementation. This is the answer I came up with. I would just like to hear comments/suggestions/opinions on this. Especially, if there is a way to optimize my answer.
public static String toBinaryString(int n){
String binary = "";
if(n == 0) return "0";
// I know, I'm desperate :(
if(n == Integer.MIN_VALUE) return "10000000000000000000000000000000";
if(n < 0){
// Get the positive equivalent
int val = n * -1;
// Convert into binary
String initial = toBinaryString(val);
String inverted = "";
// Get 1's complement
for(char chars : initial.toCharArray()){
inverted += String.valueOf(((chars == '1') ? '0' : '1'));
}
int carry = 0;
/*Check least significant bit.
If 0, simply change it to 1.
If 1, perform addition of 0b1*/
if(inverted.charAt(inverted.length()-1) == '1'){
boolean carriedOver = false;
for(char chars : new StringBuilder(inverted).reverse().toString().toCharArray()){
if(carriedOver){
binary = chars + binary;
continue;
}
if(carry > 0){
if(chars == '1'){
binary = "0" + binary;
continue;
}else{
binary = "1" + binary;
carriedOver = true;
continue;
}
}
binary = "0" + binary;
carry += 1;
}
}else{
StringBuilder sb = new StringBuilder(inverted);
sb.setCharAt(inverted.length()-1, '1');
binary = sb.toString();
}
return String.format("%32s", binary).replace(" ", "1");
}
// Convert to binary
while(n > 0){
binary = (n & 1) + binary;
n /= 2;
}
return binary;
}
If you were our senior developer, would you accept this as a valid answer? Why? Why not?
while (n > 0)
will work for negative numbers, too. Have you tried removing yourif (n < 0)
block and changingwhile (n > 0)
towhile (n != 0)
? – Tanner Swett yesterday