Can Someone Help Me Understand This Java Code for Binary Addition?

0
0
Asked By CuriousCoder88 On

Hey everyone, I'm trying to grasp this Java code that sums two binary numbers, but I'm struggling to understand it. Here's the code:

```java
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");
}
}
```

I really can't explain what it's doing, especially the part about array size, and I'd appreciate any insights!

1 Answer

Answered By TechiePal123 On

This code is designed to take two binary numbers, add them digit by digit, and store the result in an array. The array size is set to 20 to accommodate the maximum number of binary digits it might handle, assuming the binary numbers are not too long. Each step adds the rightmost bits of the two numbers along with any remainder from the previous addition, and it continues until all digits are processed. In the end, it prints the sum in reverse order because that's how it was built up in the array. It's a neat algorithm!

BinaryGeek99 -

I agree, but I'm curious why they specifically picked 20. Is that a standard size for binary sums, or could it be smaller or larger depending on the context?

CuriousCoder88 -

Thanks for clarifying! I'll definitely look more into the logic and try running the code myself.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.