标签:
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‘; } };
以上方法Memory Limit Exceeded
修改后方法如下:
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‘; } };
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4483424.html