码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Add Binary |My Solution

时间:2014-10-23 17:47:23      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   java   for   

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

标签:style   blog   http   color   io   os   ar   java   for   

原文地址:http://blog.csdn.net/aresgod/article/details/40399811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!