首页 > 代码库 > LeetCode Add Binary |My Solution

LeetCode Add Binary |My Solution

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

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

Show Tags
Have you been asked this question in an interview? 

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;
        }
        int addBits = Math.min(a.length(), b.length());
        StringBuffer sb = new StringBuffer();
        int bitPlus = 0;
        for (int i = 0; i < addBits; i++) {
          int aBit = a.charAt(a.length() - 1 - i) - '0';
          int bBit = b.charAt(b.length() - 1 - i) - '0';
          int cur = aBit + bBit + bitPlus;
          bitPlus = cur / 2;
          cur = cur % 2;
          sb.insert(0, String.valueOf(cur));
        }
      return  doOther( a,  b, addBits, bitPlus, sb); 
        
    }
    public String doOther(String a, String b, int addBits,int bitPlus,StringBuffer sb) {
        if (b.length() > a.length()) {
            doOther( b, a, addBits, bitPlus, sb); 
        } else {
            for (int i = addBits; i < a.length();i++)
            {
             int aBit = a.charAt(a.length() - 1 - i ) - '0';
             int cur = aBit + bitPlus;
             bitPlus = cur / 2;
             cur = cur % 2;
             sb.insert(0,String.valueOf(cur));
            }
            if (bitPlus == 1) {
                sb.insert(0,"1");
            }
            return sb.toString();
        }
        return sb.toString();

    }
}


LeetCode Add Binary |My Solution