Sunday, March 8, 2015

67. Add Binary Leetcode Java

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Solution:
Basically, it is add two numbers in binary form. Carry=sum/2; digit=sum%2. 
Tips: String processing direction: from end to start. 
 public String addBinary(String a, String b) {  
    if(a==null || a.length()==0) return b;  
    if(b==null || b.length()==0) return a;  
    int sum=0;  
    int carry=0;  
    int la=a.length()-1;  
    int lb=b.length()-1;  
    StringBuilder sb=new StringBuilder();  
    while(la>=0 || lb>=0 || carry>0){  
      int num1=(la>=0)? a.charAt(la--)-'0' : 0;  
      int num2=(lb>=0)? b.charAt(lb--)-'0' : 0;  
      sum=num1+num2+carry;  
      carry=sum/2;  
      sb.append(sum%2);  
    }  
     return sb.reverse().toString();  
   }  

No comments:

Post a Comment