Package addBinary67;
/*
Given binary strings, return their sum (also a binary string).
For example,
A = "11"
b = "1"
Return "100".
*/
public class Solution {
public static string Addbinary (string A, string b) {
Ensure A.length () <=b.length ()
if (A.length () >b.length ())
Return Addbinary (B,a);
Char[] Chara=a.tochararray ();
Char[] Charb=b.tochararray ();
int lena=chara.length;
int lenb=charb.length;
StringBuilder sb=new StringBuilder ();
int carry=0;
Add the same length numbers
for (int i=0;i<lena;i++) {
int inta=chara[lena-1-i]-' 0 ';
int intb=charb[lenb-1-i]-' 0 ';
Sb.append (Inta^intb^carry);
carry= (INTA&INTB) | ((INTA^INTB) &carry);
}
Add the longer length numbers
for (int i=lenb-lena-1;i>=0;i--) {
int intb=charb[i]-' 0 ';
Sb.append (Intb^carry);
carry=intb&carry;
}
Judge the first bit
if (carry>0)
Sb.append (carry);
Return Sb.reverse (). toString ();
}
public static void Main (string[] args) {
TODO auto-generated Method Stub
String a= "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
String b= "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011";
String a= "101";
String b= "10111";
System.out.println (Addbinary (A, b));
110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000
}
}
Leetcode----67. Add Binary (Java)