Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100" .
Hide TagsMath String
solution in Java:
public class Solution {public string addbinary (string A, string b) {int lengtha = A.length (); int LENGTHB = B.length (); int minLength, maxLength; String Minstr, Maxstr; if (LENGTHA<=LENGTHB) {minLength = Lengtha; Minstr = A; MaxLength = LENGTHB; Maxstr = b; }else{minLength = LENGTHB; Minstr = b; MaxLength = Lengtha; Maxstr = A; } String sum= ""; Boolean carry = false; for (int i=0; i<minlength; i++) {int digi1 = Minstr.charat (minlength-i-1)-' 0 '; int digi2 = Maxstr.charat (maxlength-i-1)-' 0 '; int Sumdigi; if (carry) Sumdigi = digi1+digi2+1; else Sumdigi = Digi1+digi2; if (sumdigi/2>0) carry = true; else carry = false; Sumdigi = sumdigi%2; String Curdigi = string.valueof (Sumdigi); sum = Curdigi +sum; } for (int i=maxlength-minlength-1; i>=0; i--) {int digi = Maxstr.charat (i)-' 0 '; if (carry) digi = digi+1; if (digi==2) {digi=0; carry = true; } else carry = false; String Curdigi = string.valueof (digi); sum = curdigi+sum; } if (carry) sum = "1" +sum; return sum; }}
Note:originally wanted to directly use the binary in Java, the conversion between decimal and string, the function is:binary to decimal: int I=integer.parseint (str, 2) The second parameter is the binary tree decimal number Turn binary string:string binstr = integer.tobinarystring (i) but not in this problem, because two input parameters may exceed the range of int and long, numberformatexception can occur, and can only be manipulated directly on a string. gets the character of a bit of string Str.charat (i), gets the int value of char, which can be subtracted ' 0 ' from this char, and the value of 0 or 1 of that bit can be obtained. Char can be subtracted directly. int to string with function string str= string.valueof (i)Note that this addition is to be done from the end of the string to the beginning
Question 30th Add Binary