67Add Binary
来源:互联网 发布:枫叶知秋 编辑:程序博客网 时间:2024/05/19 20:40
题目链接:https://leetcode.com/problems/add-binary/
题目:
Given two binary strings, return their sum (also a binary string).For example,a = "11"b = "1"Return "100".
解题思路:
这题的思路已经用过很多次了。比如,大整数加法,十进制字符串相加等。
- 把两个字符串从右向左遍历,进行加和,直到至少有一个字符串遍历完成为止。注意有进位。
- 此时应检查是否还有另一个字符串没有被遍历完。若发现存在则继续遍历。
- 遍历完两个字符串后,还需检查进位是否为 0,若进位不为 0,还要加上进位。
- 保存加和完的结果,我采用了 StringBuilder 这样的数据结构。一开始想用 append 方法,但是想到还要对字符串进行逆置,稍显麻烦。后发现了另一个方法 insert,可以将每次加和的结果直接插入到第一个字符的位置,这样从一开始结果字符串就是逆序存放的。
StringBuilder insert(int offset, int i)
Inserts the string representation of the second int argument into this sequence.
看了大神的做法,其实用 StringBuilder 的 reverse 方法速度方面也不会有太大影响。
代码实现:
public class Solution { public String addBinary(String a, String b) { if(a == null || b == null || a.length() == 0 || b.length() == 0) return null; int aLen = a.length(); int bLen = b.length(); StringBuilder sb = new StringBuilder(); int carry = 0; int i = 0; for(; i < aLen && i < bLen; i ++) { int sum = (a.charAt(aLen - 1 - i) - '0') + (b.charAt(bLen - 1 - i) - '0') + carry; sb.insert(0, sum % 2); carry = sum / 2; } while(i < aLen) { int sum = (a.charAt(aLen - 1 - i) - '0') + carry; sb.insert(0, sum % 2); carry = sum / 2; i ++; } while(i < bLen) { int sum = (b.charAt(bLen - 1 - i) - '0') + carry; sb.insert(0, sum % 2); carry = sum / 2; i ++; } if(carry != 0) sb.insert(0, carry); return sb.toString(); }}
294 / 294 test cases passed.Status: AcceptedRuntime: 5 ms
0 0
- [67]Add Binary
- CODE 67: Add Binary
- [leetcode 67] Add Binary
- 67、Add Binary
- [LeetCode 67]Add Binary
- leetcode-67 Add Binary
- leetcode || 67、Add Binary
- LeetCode 67 Add Binary
- Add Binary - LeetCode 67
- #67 Add Binary
- LeetCode---(67) Add Binary
- leetcode[67]:Add Binary
- 67Add Binary
- leetcode 67 Add Binary
- Leetcode# 67 Add Binary
- leetcode 67: Add Binary
- leetcode-67-Add Binary
- 67Add Binary
- 汉语字典
- quartz_jobs.xml配置文件样例2--CronTrigger
- 九度OJ 1030:毕业bg (01背包、DP)
- C#中的 int? int??是什么意思
- iOS8以后第三方键盘,获取高度为0的问题
- 67Add Binary
- Mvc Html.BeginForm 方式提交Form前验证
- POJ 2159
- linux文件的隐藏属性chattr,lsattr
- iOS开发常用的集中设计模式
- UFT工具
- Android学习Broadcast Receiver(广播接收者) 注意事项
- maven报错
- 测试对象管理—共享对象库