Given two binary strings, return their sum (also a binary string ).
For example,
A ="11"
B ="1"
Return"100"
.
String addition, not difficult
Personal thoughts:
1. Tail alignment, and then add one by one. Flag is marked as carry.
Code:
1 # include <string> 2 3 using namespace STD; 4 5 class solution {6 public: 7 string addbinary (string a, string B) {8 if (. empty () 9 {10 return B; 11} 12 if (B. empty () 13 {14 return a; 15} 16 17 int Alen =. length (); 18 int blen = B. length (); 19 int I = Alen-1, j = blen-1; 20 int flag = 0; // carry 21 int temp, AI, BJ; 22 string result; 23 24 for (; I> = 0 | j> = 0; -- I, -- j) 25 {26 AI = I> = 0? (A [I]-'0'): 0; 27 bj = j> = 0? (B [J]-'0'): 0; 28 29 temp = ai + BJ + flag; 30 flag = temp> 1? 1: 0; 31 temp = temp-flag * 2; 32 33 result. insert (result. begin (), temp + '0'); 34} 35 36 IF (FLAG) 37 {38 result. insert (result. begin (), '1'); 39} 40 41 return result; 42} 43 };
View code
Leetcode-add binary