67. Add Binary
2016-01-15 14:38
225 查看
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
For example,
a = “11”
b = “1”
Return “100”.
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; StringBuilder sb = new StringBuilder(); int la = a.length(),lb = b.length(),add = 0; int i = la-1,j = lb-1; while(i >= 0 || j >= 0 || add != 0){ int ta = i >= 0?a.charAt(i)-'0':0; int tb = j >= 0?b.charAt(j)-'0':0; int tr = ta^tb^add; add = (ta+tb+add) > 1?1:0; //进位 sb.append(tr); i--; j--; } return sb.reverse().toString(); } }
相关文章推荐
- Android SlidingMenu 史上最简单实现方式
- 在sublime Text2上配置并运行Java程序
- Webview 支持 input type=file
- Unity3d OnApplicationPause与OnApplicationFocus
- myeclipse unhandled event loop exception
- 重新学习git-远程仓库
- P2P UPD打洞原理
- [bzoj2141]排队
- CentOS 6.2图形界面允许root用户登录
- Linux磁盘分区
- oracle入门
- 基于nginx tomcat redis分布式web应用的session共享配置
- oracle入门
- gRPC异步处理应答
- C++编译期多态与运行期多态
- gRPC异步处理应答
- 平时关注网站汇总
- 动态设置Android状态栏颜色
- oracle运用(四) oracle数据库NUMBER类型详解
- 【Western Digital】三角板自校准标准流程