Class Solution {Public:string addbinary (string A, string b) {int car = 0; int cur_a = A.length ()-1; int cur_b = B.length ()-1; int num = 0; string ret = ""; while (cur_a>=0 && cur_b>=0) {int toa = 0; if (cur_a >= 0) {toa = Char2int (a[cur_a--]); } int tob = 0; if (cur_b >= 0) {Tob = Char2int (b[cur_b--]); } num =car + toa + tob; num = num% 2; RET = ret + (char) num + (char) car; Car =NUM/2; } while (Cur_a >=0) {int toa; Toa = Char2int (a[cur_a]); Num =car + toa; num = num% 2; RET = ret + (char) num + (char) car; Car =NUM/2; } while (Cur_b >= 0) {int Tob; Tob = Char2int (B[cur_b]); Num =car + tob; num = num% 2; RET = ret + (char) num + (char) car; Car =NUM/2; } return ret; } int Char2int (char c) {return c ' 0 '; } char Int2char (bool b) {if (b) {return ' 1 '; } return ' 0 '; }};
Above method memory Limit exceeded
The following methods are modified:
Class Solution {Public:string addbinary (string A, string b) {int car = 0; int cur_a = A.length ()-1; int cur_b = B.length ()-1; int num = 0; string ret; int toa = 0; int tob = 0; while (cur_a>=0 && cur_b>=0) {if (cur_a >= 0) {toa = Char2int (a[cur_a--]); } if (cur_b >= 0) {Tob = Char2int (b[cur_b--]); } num =car + toa + tob; Car =NUM/2; num = num% 2;ret.insert (ret.begin (), Int2char (num)); /* ret = RET + int2char (num); */} while (Cur_a >=0) {toa = Char2int (a[cur_a]); Num =car + toa; Car =NUM/2; num = num% 2;ret.insert (ret.begin (), Int2char (num)); /*ret = ret + int2char (num); */cur_a--; } while (Cur_b >= 0) {Tob = Char2int (B[cur_b]); Num =car + Tob Car =NUM/2; num = num% 2;ret.insert (ret.begin (), Int2char (num)); /*ret = ret + int2char (num); */cur_b--; } if (car = = 1) ret.insert (Ret.begin (), ' 1 '); /*ret + = ' 1 '; */return ret; } int Char2int (char c) {return c ' 0 '; } char Int2char (int b) {if (b) {return ' 1 '; } return ' 0 '; }};
(Leetcode) ADD Binary