[leedcode 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) {
        //时间复杂度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();
    }
}

 

你可能感兴趣的:(binary)