Leetcode ADD Binary

Source: Internet
Author: User

1. Topics


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

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


2. Solutions
Class Solution {Public:char inttochar (int input) {char strbuffer[1] = {0};        sprintf (Strbuffer, "%d", input);    return strbuffer[0];        } string Addb (string A, string b) {string result;                for (int i = A.size ()-1; I >=0; i.) {int adigital = a[i]-' 0 ';                int bdigital = b[i]-' 0 ';                int sumresult = adigital + bdigital;                    if (Sumresult >= 2) {if (Sumresult = = 2) {result.push_back (' 0 ');                    }else{result.push_back (' 1 ');                    } if (i-1 >= 0) {a[i-1] = Inttochar (a[i-1]-' 0 ' + 1);                    }else{result.push_back (' 1 ');                }}else{Result.push_back (Inttochar (Sumresult));        }} reverse (Result.begin (), Result.end ());    return result; } StRing Addbinary (String A, string b) {size_t Sizea = a.size ();                size_t Sizeb = B.size ();                Unequal alignment if (Sizea > Sizeb) {b.insert (B.begin (), Sizea-sizeb, ' 0 '); } else if (Sizea < Sizeb) {A.insert (A.begin (), Sizeb-si                ZeA, ' 0 ');    } return Addb (A, b); }};

1. Here are some tricks, the first is to put a short string in front of 0, using the Insert method. Then it is according to the manual addition method, starting from the last one, if greater than or equal to 2, the number of the previous digit plus 1. The final result is reversed. If you know that a char is a number, for example, to turn ' 9 ' into an int of 9, you can put ' 9 '-' 0 '.

http://www.waitingfy.com/archives/1686

Leetcode ADD Binary

Related Article

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.