Add Binary
来源:互联网 发布:js怎么调用java的方法 编辑:程序博客网 时间:2024/06/09 22:16
Q:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution:
public class Solution { public String addBinary(String a, String b) { String result = ""; int i = a.length() - 1; int j = b.length() - 1; int carry = 0; while (i >= 0 || j >= 0) { int ai = i >= 0? a.charAt(i) - '0': 0; int bj = j >= 0? b.charAt(j) - '0': 0; int bit = (ai + bj + carry) % 2; carry = (ai + bj + carry) / 2; result = bit + result; i--; j--; } if (carry == 1) result = carry + result; return result; }}
0 0
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- CentOS下安装 ImageMagick时 缺失 freetype的解决方法
- DOM基本属性笔记
- apache 2.4.9 配置
- LeetCode Reverse Words in String (Java)
- 分析模式 - 度量与测绘
- Add Binary
- C9_指针高级
- iOS面试总结 - 3. iOS高级面试题
- C之谜题(持续更新)
- c++ 和 c#参数对照表
- hdu 3416 Marriage Match IV 【网络最大流+最短路】
- 解题报告
- 分析模式 - 库存和账务模式
- hdu1026 bfs