program to add two binary numbers

Solutions on MaxInterview for program to add two binary numbers by the best coders in the world

showing results for - "program to add two binary numbers"
Niko
04 Oct 2018
1class Solution {
2    public String addBinary(String a, String b) {
3        int i=a.length()-1;
4        int carry=0;
5        int j=b.length()-1;
6        int sum=0;
7        StringBuilder sb=new StringBuilder();
8        while(i>=0 || j>=0){
9            sum=carry;
10            if(i>=0){
11                sum+=a.charAt(i)-'0';
12            }
13             if(j>=0){
14                sum+=b.charAt(j)-'0';
15            }
16            sb.append(sum%2);
17            carry=sum/2;
18            i--;
19            j--;
20        }
21        if(carry!=0){
22            sb.append(carry);
23        }
24        return sb.reverse().toString();
25    }
26}