Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, April 30, 2018

add two Binary Strings


First make their length equal by appending 0 at start
then perform addition


Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class binaryAddition
 {
   public static StringBuffer addZero(StringBuffer a,int len)
   {
     String str=new String();
     while(len-->0)
     {
       str+='0';
     }
     a.insert(0,str);
     return a;
   }
   public static StringBuffer addBinary(StringBuffer a,StringBuffer b)
   {
     if(a.length()<b.length())
     {
       a=addZero(a,b.length()-a.length());
     }
     if(b.length()<a.length())
     b=addZero(b,a.length()-b.length());
     //System.out.println(a);
     //System.out.println(b);
     //now add binary strings
     StringBuffer res=new StringBuffer();
     int carry=0;
     for(int i=a.length()-1;i>=0;--i)
     {
       res.append(String.valueOf((carry+a.charAt(i)+b.charAt(i)-'0'-'0')%2));
       carry=(carry+a.charAt(i)+b.charAt(i)-'0'-'0')/2;
    //   System.out.println("carry "+carry);
     }
     if(carry==1)
     res.append('1');
     return res.reverse();
   }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
    System.out.println(addBinary(new StringBuffer(ab.next()),new StringBuffer(ab.next())));
}
}
}

0 Comments:

Post a Comment

Stats