LeetCode 067 Add Binary
来源:互联网 发布:伟大的艺术家 知乎 编辑:程序博客网 时间:2024/05/21 07:05
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
二进制数加减函数完成,输入输出都是字符串
1 这道题考察点有几个:
a String StringBuffer char[]的区别。基本碰到此类题目,如果允许我都使用StringBuffer来做,自带了很多方便的方法,它底层对象是char[],所以不像String的反复修改会产生新的字符串对象。
b 坐标的位子 从 0- n-1 而不是n
c 加法的进位处理
d 二进制加法的原则
2 原先的代码:
public class Solution { public String addBinary(String a, String b) { int al = a.length(); int bl = b.length(); if(al==0){ return b; } if(bl==0){ return a; } if(al<bl){ String temp =a; a = b; b = temp; int l = al; al = bl; bl =l; } int c = 0; StringBuffer ans = new StringBuffer(); for(int i=1;i<=bl;i++){ int acur = a.charAt(al-i)-'0'; int bcur = b.charAt(bl-i)-'0'; int newcur = (acur+bcur+c)%2; c = (acur+bcur+c)/2; ans.append(newcur); } for(int i=al-bl-1;i>=0;i--){ int acur = a.charAt(i)-'0'; int newcur = (acur+c)%2; c = (acur+c)/2; ans.append(newcur); } if(c==1){ ans.append("1"); } return new String(ans.reverse()); }}
好几次后才通过,碰到的情况有:
a charAt() 写成 chartAt[]
b al和bl 的交换忘记进行
c reverse忘记加了。
3 看了大牛的博客,发觉我这样的写法太弱了!只需要三个坐标,对应两个加数,每次加的时候,判断一下加的内容是否还在即可。终止条件是所有加数和进位都为0。另外,判断是否进位的时候,判断>1 会比%2 /2的好
public class Solution { public String addBinary(String a, String b) { if(a.length()==0){ return b; } if(b.length()==0){ return a; } int i = a.length()-1; int j = b.length()-1; int c = 0; StringBuffer ans = new StringBuffer(); while(true){ if(i<0&&j<0&&c==0){ break; } int acur =0; int bcur =0; if(i>=0){ acur= a.charAt(i)-'0'; } if(j>=0){ bcur= b.charAt(j)-'0'; } if(acur+bcur+c>1){ ans.append(acur+bcur+c-2); c=1; } else{ ans.append(acur+bcur+c); c=0; } i--; j--; } return new String(ans.reverse()); }}
0 0
- LeetCode 067 Add Binary
- LeetCode 067 Add Binary
- LeetCode 067 Add Binary
- leetcode 067 Add Binary
- leetcode 067 Add Binary
- LeetCode 067 Add Binary
- 20170218-leetcode-067:Add Binary
- leetcode 067 —— Add Binary
- leetcode解题方案--067--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 58: Add Binary
- title_test2055110740
- title_test667198578
- title_test-1168853915
- title_test944542468
- 115家电子科技企业待遇一览
- LeetCode 067 Add Binary
- Content Provider Basics
- 一个Sqrt函数引发的血案
- OJ_1036
- error LNK2005
- 如何避免僵尸进程
- Leetcode Maximum Depth of Binary Tree
- Spring MVC 与 itextpdf 集成实现PDF签名的maven包依赖冲突
- 指定Action、Category调用系统Activity实例-点击按钮,返回Home桌面