首页 > 代码库 > 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
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。