[leedcode 67] Add Binary

3004 ワード

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) {
        // O(n)。 O(1)
        // :1. , , , , 
        //2. 
        //3. stringBuilder 
        StringBuilder seq=new StringBuilder();
        int carry=0;
        int i=a.length()-1;
        int j=b.length()-1;
       /* for(;j>=0&&i>=0;i--,j--){
            int a1=a.charAt(i)-'0';
            int b1=b.charAt(j)-'0';
            int temp=a1+b1+carry;
            seq.insert(0,temp%2);
            carry=temp/2;
        }
        while(i>=0){
            int temp=a.charAt(i)-'0'+carry;
            seq.insert(0,temp%2);
            carry=temp/2;
            i--;
        }
        while(j>=0){
            int temp=b.charAt(j)-'0'+carry;
            seq.insert(0,temp%2);
            carry=temp/2;
            j--;
        }*/
        for(;j>=0||i>=0;i--,j--){
            int a1=i>=0?a.charAt(i)-'0':0;
            int b1=j>=0?b.charAt(j)-'0':0;
            int temp=a1+b1+carry;
            seq.insert(0,temp%2);
            carry=temp/2;
        }
        if(carry>0) seq.insert(0,carry);
        return seq.toString();
    }
}