Leetcode----67. Add Binary (Java)

Source: Internet
Author: User

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&AMP;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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.