67. Add Binary
2016-04-07 21:31
337 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
For example,
a =
"11"
b =
"1"
Return
"100".
public class Solution { public String addBinary(String a, String b) { if (a == null || a == "") return b; if (b == null || b == "") return a; int carry = 0; String ret = ""; int l1 = a.length()-1; int l2 = b.length()-1; while (l1 >= 0 || l2 >= 0 || carry == 1) { if (l1 >= 0) { carry += Integer.parseInt(a.charAt(l1)+""); l1--; } if (l2 >= 0) { carry += Integer.parseInt(b.charAt(l2)+""); l2--; } ret = String.valueOf(carry%2) + ret; carry /= 2; } return ret; } }
相关文章推荐
- android工具库
- 轻松学习之 IMP指针的作用
- 简单Python3爬虫程序(3)进阶:登录、解压缩、cookies
- poj1852ants
- 自己实现android侧滑菜单
- Collections.sort()及map.Entry<>用法
- c#泛型约束
- C语言中内存以及堆栈情况
- 尚硅谷·网上书城项目(二)
- Leetcode no. 26
- 链表2
- sqlplus / as sysdba 命令详解
- bzoj4500 矩阵
- Django学习笔记 创建应用
- C++中public、protected及private使用方法
- 关于构建AABB树过程中内存优化
- atitit. web组件化原理与设计
- new/delete重载
- new/delete重载
- java简易项目总计