[LeetCode]Add Binary
来源:互联网 发布:知安天下 编辑:程序博客网 时间:2024/05/29 14:50
题目描述
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题思路
将两个字符串从后向前扫描,相同位的字符变为数字后进行相加运算,需要考虑到进位和两字符串不等长的情况。
代码
public static String addBinary(String a, String b) {String result = "";if (a == null && b == null) {return null;} else {if (a == null)return b;if (b == null)return a;} int x = 0, y = 0, add = 0;for(int i = a.length() - 1,j = b.length() - 1; i >= 0 || j >=0;i--,j--){x = 0;if (i >= 0) {x = a.charAt(i) - '0';}y = 0;if (j >= 0) {y = b.charAt(j) - '0';}result = (x + y + add) % 2 + result;add = (x + y + add) / 2;}if (add == 1) {result = 1 + result;}return result;}
0 0
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- crontab题
- C++、Objective-c混编陷阱之–错误的头文件引用
- Android4.2.2 SurfaceFlinger之图形渲染queueBuffer实现和VSYNC的存在感
- 记住密码的实现
- 使用DetailsView单页编辑控件
- [LeetCode]Add Binary
- 无线路由找不到无线网络的原因
- BI工具:tableau桌面版 视频学习笔记(二、分析)
- js实现表单项的全选、反选以及删除操作
- block写法
- 模式设计相关网站
- 嵌入式web服务器boa的测试
- NS2中几个重要的类
- Android源码编译整理总结