Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题目本身还是比较简单的,就是二进制加法,不过写程序的时候发现自己对字符串的api还是有点生疏,贴出来以便复习用吧~注意一下进位的取值就可以了。
public String addBinary(String a, String b) { String res=new String(); int exceed = 0; int bits=0; int indexa = a.length() - 1, indexb = b.length() - 1; while (indexa >= 0 && indexb >= 0) { int result = a.charAt(indexa)-'0'+b.charAt(indexb)-'0'+exceed; bits=result%2; exceed=result/2; res=""+bits+""+res; indexa--; indexb--; } while(indexa>=0) { int result = exceed + a.charAt(indexa)-'0'; bits=result%2; exceed=result/2; res=""+bits+""+res; indexa--; } while(indexb>=0) { int result = exceed + b.charAt(indexb)-'0'; bits=result%2; exceed=result/2; res=""+bits+""+res; indexb--; } if(exceed==1) res=""+exceed+""+res; StringBuffer str=new StringBuffer(); return res; }