-1

This program is about binary addition in Java:

public static String binaryAddition(String s1, String s2) {
    if (s1 == null || s2 == null) return "";
    int first = s1.length() - 1;
    int second = s2.length() - 1;
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    while (first >= 0 || second >= 0) {
        int sum = carry;
        if (first >= 0) {
            sum += s1.charAt(first) - '0';
            first--;
        }
        if (second >= 0) {
            sum += s2.charAt(second) - '0';
            second--;
        }
        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');
    }
    if (carry > 0)
        sb.append('1');

    sb.reverse();
    return String.valueOf(sb);
}

I am having difficulty in understanding this program.

Why we have to substract with 0 here?

sum += s1.charAt(first) - '0';

What is the use of >> operator and & operator here:

        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');

Can you please help me in understanding this program.

1 Answer 1

0

Why we have to subtract with 0 here?

 sum += s1.charAt(first) - '0';

That is converting the characters '0' and '1' to the numbers 0 and 1.

What is the use of >> operator and & operator here:

The >> is shifting one bit to the right, and the & is masking out all bits apart from the rightmost one.

Can I recommend that you find and read a tutorial on how bitwise operations work in Java. This is very basic stuff. Once you understand the basics, then you should be able to read and understand code like the code you have shown us.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, can you please explain how the >> and & in solving binary addition here. I understand how the operator works but not clear how this is solving this addition program.
Clearly, those two statements are figuring out what the carry bit is. Have you read anything about how binary addition works? en.wikipedia.org/wiki/Binary_number#Addition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.