lintcode-easy-Add Binary
2016-02-18 17:53
246 查看
Given two binary strings, return their sum (also a binary string).
Example
a =
b =
Return
这道题也没太多好说的……
Example
a =
11
b =
1
Return
100
这道题也没太多好说的……
public class Solution { /** * @param a a number * @param b a number * @return the result */ public String addBinary(String a, String b) { // Write your code here if(a == null) return b; if(b == null) return a; if(a.length() == 0) return b; if(b.length() == 0) return a; int p1 = a.length() - 1; int p2 = b.length() - 1; StringBuilder result = new StringBuilder(); int carry = 0; while(p1 >= 0 || p2 >= 0){ int bit_a = 0; int bit_b = 0; if(p1 >= 0){ bit_a = (int) (a.charAt(p1) - '0'); p1--; } if(p2 >= 0){ bit_b = (int) (b.charAt(p2) - '0'); p2--; } result.insert(0, (bit_a + bit_b + carry) % 2); carry = (bit_a + bit_b + carry) / 2; } if(carry == 1) result.insert(0, 1); return result.toString(); } }
相关文章推荐
- HTMl5的sessionStorage和localStorage
- 探秘Java中String、StringBuilder以及StringBuffer
- iOS 【UIKit-一个控件用肉眼看不见,有哪些可能】
- 第一个Linux驱动-流水灯【转】
- Linux权限管理
- HDU2087(KMP入门题)
- 利用批处理实现按当前日期创建目录并备份
- Immutable 详解及 React 中实践
- 转载http://www.cnblogs.com/kenshincui/p/3931948.html
- 社区
- Unity接入Admob广告教程IOS篇
- 简约才是王道? CardView 的使用
- 5.2类与对象---对象和C语言中的指针变量的比较
- 简约才是王道? CardView 的使用
- Android WebView开发问题及优化汇总
- Android 窗口管理
- LVS+Keepalived+Squid+Nginx+MySQL主从高性能集群架构部署方案
- git bisect
- Linux下c开发之——线程间通信
- OkHttp使用教程