I am beginner at Java. While doing some exercises on w3resource i came across on problem that puzzles me. Basically I need to input two binary numbers and add them. I would like to know is there easier way to do this without inputing binary numbers as long variables,(as it is in given solution to this exercise) and if there is not easier way could someone explain part where while loop is used to the end of the code?
Thanks in advance!
/*given solution*/
import java.util.Scanner;
public class Exercise17 {
public static void main(String[] args)
{
long binary1, binary2;
int i = 0, remainder = 0;
int[] sum = new int[20];
Scanner in = new Scanner(System.in);
System.out.print("Input first binary number: ");
binary1 = in.nextLong();
System.out.print("Input second binary number: ");
binary2 = in.nextLong();
while (binary1 != 0 || binary2 != 0)
{
sum[i++] = (int)((binary1 % 10 + binary2 % 10 + remainder) % 2);
remainder = (int)((binary1 % 10 + binary2 % 10 + remainder) / 2);
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0) {
sum[i++] = remainder;
}
--i;
System.out.print("Sum of two binary numbers: ");
while (i >= 0) {
System.out.print(sum[i--]);
}
System.out.print("\n");
}
}
Strings instead. Then you can just pull the "1"s and "0"s directly out of them, instead of doing all that remaindering and dividing by 10. And you wouldn't be limited to the 18 or so digits that alongcan hold.