Reputation: 25
I was doing some java coding exercises and this add 2 binary number exercise. I am not sure why the if condition is always false, even if I put actual int into the variable.
whats the problem???
public class Main {
public static void main(String[]args){
long bin1 = 10, bin2 = 101;
int carry = 0, i = 0;
int bin1Length = String.valueOf(bin1).length();
int bin2Length = String.valueOf(bin2).length();
int length;
System.out.println("bin1: " + bin1Length);
System.out.println("bin2: " + bin2Length);
if(bin1Length > bin2Length){ // not sure why its always false in all 3 conditions
length = bin1Length;
} else if (bin2Length < bin1Length){
length = bin2Length;
} else if (bin1Length == bin2Length){
length = bin1Length;
}
int [] finalOutput = new int [length];
while(bin1 != 0 || bin2 != 0){
finalOutput[i++] = (int)(carry + (bin1 % 10 + bin2 % 10) % 2);
carry = (int)((carry + bin1 % 10 + bin2 % 10)/2);
bin1 = bin1/10;
bin2 = bin2/10;
}
if(carry != 0){
finalOutput[i] = carry;
}
System.out.print("Output: ");
while(i >= 0){
System.out.print(finalOutput[i--]);
}
}
}
Thanks.
Upvotes: 0
Views: 1647
Reputation:
bin1Length is 2 and bin2Length is 3. That's why the if condition will always be false.
Also, optimized code would be:
length = bin1Length;
if (bin2Length > bin1Length)
length = bin2Length;
Upvotes: 0
Reputation: 1764
your first if
condition and the following else if
are the same.
have a better look on this:
if(bin1Length > bin2Length){
length = bin1Length;
} else if (bin2Length < bin1Length){
length = bin2Length;
}
if bin1Length
won't be greater than bin2Length
, of course bin2Length
is not smaller than bin1Length
.
change it to this:
if(bin1Length > bin2Length){
length = bin1Length;
} else if (bin1Length < bin2Length){
length = bin2Length;
} else if (bin1Length == bin2Length){
length = bin1Length;
}
Upvotes: 4