"Leetcode" 67. ADD Binary

Source: Internet
Author: User

Title:

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

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

Tips:

My first reaction to this question is to convert the input two string into a number, add the result into a binary output, but there will be a lot of input in the test case, even if a long long type can also cause overflow, so can only use the most traditional from low to high position to add the method to do.

Code:
classSolution { Public:    stringAddbinary (stringAstringb) {intLen_a = A.size ()-1, Len_b = B.size ()-1; intDIF = ABS (Len_a-Len_b); stringPrev ="";  for(inti =0; i < dif; ++i) Prev + ='0'; if(Len_a < Len_b) A = prev +A; Elseb = prev +b; intLen = a.size (), step =0; Vector<int>v;  for(inti = len-1; I >-1; --i) {step+ = A[i] + b[i]-('0'<<1); V.push_back (Step%2); Step= Step >>1; }        if(step) v.push_back (step%2); stringRes;  for(inti = v.size ()-1; I >-1; --i) {res+= ('0'+V[i]); }        returnRes; }};

"Leetcode" 67. 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.