LeetCode: 67. Add Binary, leetcodebinary
Question:
Given two binary strings, return their sum (also a binary string ).
For example,
A ="11"
B ="1"
Return"100".
This topic is a string operator bitwise operation. It is unclear if Python is closed, and it will be difficult to implement it. If Java can directly perform binary operations like C/C ++, it is also a concept. At the beginning, I did not think it would work very well. In fact, I implemented a binary addition by myself, and then combined with mod 2 and I + 2 to master the carry calculation. Paste the problem-solving code in the official forum.
Solution:
Public String addBinary (String a, String B ){
StringBuilder sb = new StringBuilder ();
Int I = a. length ()-1;
Int j = B. length ()-1;
Int sum, carry = 0;
While (I> = 0 | j> = 0 ){
Sum = carry;
If (I> = 0) sum + = a. charAt (I --)-'0 ';
If (j> = 0) sum + = B. charAt (j --)-'0 ';
Sb. append (sum % 2 );
Carry = sum/2;
}
If (carry! = 0) sb. append (carry );
Return sb. reverse (). toString ();
}