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