2015年9月25日星期五

Leetcode 67 Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Solution 1: Two pointers, i and j from end of a and b. add them up to res. 
 public class Solution {  
   public String addBinary(String a, String b) {  
     int i=a.length()-1;  
     int j=b.length()-1;  
     int carry=0;  
     StringBuilder res=new StringBuilder();  
     while (i>=0 || j>=0 || carry!=0) {  
       int bit=carry;  
       if (i>=0 && a.charAt(i--)=='1') bit++;  
       if (j>=0 && b.charAt(j--)=='1') bit++;  
       res.insert(0,(char)(bit%2+'0'));  
       carry=bit/2;  
     }  
     return res.toString();  
   }  
 }  

没有评论:

发表评论