*Add Binary
2015-09-11 07:39
302 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
reference: http://rleetcode.blogspot.com/2014/02/add-binary-java.html
For example,
a =
"11"
b =
"1"
Return
"100".
public String addBinary(String a, String b) { if (a==null ||a.length()==0){ return b; } if (b==null || b.length()==0){ return a; } StringBuilder sb=new StringBuilder(); int lastA=a.length()-1; int lastB=b.length()-1; int carry=0; while (lastA>=0 ||lastB>=0 ||carry>0){ int num1=lastA>=0?a.charAt(lastA--)-'0':0; int num2=lastB>=0?b.charAt(lastB--)-'0':0; int current=(num1+num2+carry)%2; carry=(num1+num2+carry)/2; sb.insert(0, current); } return sb.toString(); }
reference: http://rleetcode.blogspot.com/2014/02/add-binary-java.html
相关文章推荐
- 【IOS 开发学习总结-OC-2】objective-c 数据类型
- C++Primer第五版 2.6.1节练习
- gradle--第7章、Java快速开始2
- C++Primer第五版 2.5.3节练习
- VS2013常用快捷键:
- 给各位聚聚和大大介绍一个开源项目 Expression2Sql
- C++Primer第五版 2.5.2节练习
- Linux 上将出现一个新的文件系统:bcachefs
- HDU 2102 A计划 (BFS + 预处理)
- C++Primer第五版 2.4.4节练习
- [LeetCode#271] Encode and Decode Strings
- C++Primer第五版 2.4.3节练习
- BZOJ 1337 最小圆覆盖 随机增量法
- C++Primer第五版 2.4.2节练习
- PHP核心知识要点
- 项目管理小知识——Alpha版本,Beta版本
- C++Primer第五版 2.4节练习
- 栈中空间大小
- 11G 单机使用asm存储 主机名发生更改并且主机重启后处理过程:
- 操作App.config与Web.config文件 - System.Configuration方式与XMLPath方式, 超强功能类