Add Binary

来源:互联网 发布:自学javascript要多久 编辑:程序博客网 时间:2024/06/04 20:02
Problem:

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

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

时间复杂度为O(max(n,m))。
Solution:
public class Solution {
    public String addBinary(String a, String b) {
        if(a==null||a.length()==0)
             return b;
        if(b==null||b.length()==0)
             return a;
        byte carry = 0;
        int p = a.length(), q = b.length();
        StringBuilder res = new StringBuilder();
        while(p>0&&q>0)
        {
             p--;q--;
             int tmp = a.charAt(p) - '0' + b.charAt(q) - '0' + carry;
             if(tmp>1)
             {
                 carry = 1;
                 res.insert(0, Integer.toString(tmp-2));
             }
             else
             {
                 carry = 0;
                 res.insert(0, Integer.toString(tmp));
             }
        }
        
        while(p>0||q>0)
        {
             p--;q--;
             int tmp = (p>=0?a.charAt(p):'0') - '0' + (q>=0?b.charAt(q):'0') - '0' + carry;
             if(tmp>1)
             {
                 carry = 1;
                 res.insert(0, '0');
             }
             else
             {
                 carry = 0;
                 res.insert(0, Integer.toString(tmp));
             }
        }
        if(carry==1)
             res.insert(0, '1');
        return res.toString();
    }
}
0 0
原创粉丝点击