[Leetcode] ADD Binary

Source: Internet
Author: User

ADD Binary

Given binary strings, return their sum (also a binary string).

For example,
A ="11"
b ="1"
Return "100" .

Problem Solving Ideas:

The test instructions is added to the binary represented by two strings, and the result is obtained. Remember that constant strings and string variables can be added, but strings cannot be added to numbers, and characters cannot be added to a string.

Class Solution {public:    string Addbinary (String A, string b) {        int len1=a.length ();        int len2=b.length ();        int carry=0;        String result= "";        int i=len1-1, j=len2-1;        while (i>=0&&j>=0) {            int r = (a[i]-' 0 ') + (b[j]-' 0 ') + Carry;            result =  (r%2==0? "0": "1") + result;            carry = R/2;            i--;            j--;        }        while (i>=0) {            int r = (a[i]-' 0 ') + Carry;            result = (r%2==0? "0": "1") + result;            carry = R/2;            i--;        }        while (j>=0) {            int r = (b[j]-' 0 ') + Carry;            result = (r%2==0? "0": "1") + result;            carry = R/2;            j--;        }        if (carry>0) {            result = "1" + result;        }        return result;}    ;


[Leetcode] Add Binary

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.