Leetcode: Add Binary
来源:互联网 发布:电信网络电视费用 编辑:程序博客网 时间:2024/06/05 09:54
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Use another string, or a stringbuilder to store the result. Start with the last characters of the two strings, and concatenate the adding result at the beginning of the new string.
public class Solution { public String addBinary(String a, String b) { if (a == null && b == null) { return null; } String res = ""; int la = a.length(); int lb = b.length(); int carry = 0; for (int i = 0; i < Math.max(la, lb); i++) { int ca = 0; int cb = 0; if (la - 1 - i >= 0) { ca = (int) (a.charAt(la - 1 - i) - '0'); } if (lb - 1 - i >= 0) { cb = (int) (b.charAt(lb - 1 - i) - '0'); } if (ca + cb + carry == 3) { res = "1" + res;; carry = 1; } else if (ca + cb + carry == 2) { res = "0" + res; carry = 1; } else { res = String.valueOf(ca + cb + carry) + res; carry = 0; } } if (carry == 1) { res = "1" + res; } return res; }}
0 0
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- hdu 1059 Dividing 多重背包
- 全国幼儿园加盟品牌排名最好的香港艾乐教育集团幼儿园教育加盟
- 每个程序员都该知道的10大编码原则
- Android笔记 apk的反编译
- 全国幼儿园加盟品牌排名最好的香港艾乐教育集团全国幼儿园加盟店
- Leetcode: Add Binary
- QQ营销中不为人知的细节和技巧
- 黑马程序员-线程
- 车牌识别行业应用受宠
- app后台任务挂起时间
- 解决困难的方式
- 小黑小波比.判断数组中是否含有一个元素
- Eclipse Plugin机制中的扩展点
- Java 单例模式