Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
恩..其實這道題可以簡單點的,用BigInteger來做..比較惡心..
但是還是乖點,用標准的做法吧
分析:
2個二進制相加,最多是進1!而且最大是數字是3 比如 11+11 = 100 最多就進1,而且最多就是3(1+1+1).
所以,寫一個函數用來計算某2個字符相加的結果,用一個私有屬性保存溢出數字(lastFlow).
好了。通過3個while來做。最後如果lastFlow不為0,那麼就要在給值.
好了.ok..
這道題其實困住我了...鞏固了
public class Solution { private int lastFlow = 0; private int add(char a,char b) { int result = a+b+lastFlow-48*2; if( result > 1) { lastFlow = 1; return result%2; } else { lastFlow = 0; return result; } } public String addBinary(String a, String b) { String result =""; int lengthOfA = a.length() - 1; int lengthOfB = b.length() -1; while(lengthOfA >=0 && lengthOfB >=0) { int temp = add(a.charAt(lengthOfA),b.charAt(lengthOfB)); result+=temp+""; lengthOfA--; lengthOfB--; } while(lengthOfA >=0 ) { int temp = a.charAt(lengthOfA)-48+lastFlow; if( temp >1) { lastFlow = 1; temp = temp%2; } else { lastFlow =0; } result +=temp+""; lengthOfA--; } while(lengthOfB >=0 ) { int temp = b.charAt(lengthOfB)-48+lastFlow; if( temp >1) { lastFlow = 1; temp = temp%2; } else { lastFlow =0; } result +=temp+""; lengthOfB--; } if( lastFlow > 0) { result+=lastFlow+""; } StringBuffer sb=new StringBuffer(result); sb=sb.reverse(); return sb.toString(); } }