Leetcode Study notes: Add Binary

Source: Internet
Author: User

I. Title Description

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

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

Two. Problem solving skills

This problem examines the addition of two binary numbers, taking into account that the input is two sets of string, while noting that the operation from left to right are from low to high, so it is necessary to consider the input to flip processing, the middle binary tree addition part of not too much design obstacles, mainly to calculate the carry; After the two sets of data are added, You also need to consider the rounding problem of the highest bit.

Three. Sample code

#include <iostream> #include <string>usingnamespaceStd;class Solution{public:stringAddbinary (stringAstringb) {size_tsize= A.size() > B.size() ? A.size(): B.size();        Reverse (A.begin (), A.end ()); Reverse (B.begin (), B.end ());intCarrybit =0;//Rounding        stringResult//For storing results         for(size_t i =0; I <size; i++) {intA_num = A.size() > I? A[i]-' 0 ':0;intB_num = b.size() > I? B[i]-' 0 ':0;intval = (a_num + b_num + carrybit)%2; Carrybit = (a_num + b_num + carrybit)/2;//RoundingResult.insert (Result.begin (), Val +' 0 '); }if(Carrybit = =1) Result.insert (Result.begin (),' 1 ');returnResult }};

Test code:

#include "AddBinary.h"using STD::cout;using STD::Cin;intMain () {stringA, B;cout<<"Input The first string:";Cin>> A;cout<<"\ninput The second string:";Cin>> b; Solution S;stringresult = S.addbinary (A, b);cout<<"\nthe Add Binary result is:"<< result;return 0;}

Several test results:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode Study notes: 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.