67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 

 

public class Solution {
    public String addBinary(String a, String b) {
         int i=a.length()-1;
        int j=b.length()-1;
        int c=0;
        String res="";
        while (i>=0||j>=0||c==1){
            if(i>=0){
                c+=a.charAt(i)-'0';
            }
            if(j>=0){
                c+=b.charAt(j)-'0';
            }
            res= (int)c%2+res;
            c/=2;
            i--;
            j--;
        }
        return res;
    }
}

 

posted on 2017-07-11 16:24  sure0328  阅读(75)  评论(0)    收藏  举报

导航