LeetCode: 67. Add Binary, leetcodebinary

Source: Internet
Author: User

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 ();

}

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.