首页 > 其他 > 详细

LeetCode Add Binary |My Solution

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!