首页 > 代码库 > leetcode -- Add Binary
leetcode -- Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution { public: string addBinary(string a, string b) { int MaxLen = (a.length()>b.length())?(a.length() + 1):(b.length() + 1); string ret(MaxLen,‘0‘);string copya(MaxLen,‘0‘);string copyb(MaxLen,‘0‘); int cursor = a.length()-1; int cursorret = MaxLen - 1; while(cursor >= 0) {copya[cursorret] = a[cursor];cursor--;cursorret--;} cursor = b.length()-1;cursorret = MaxLen - 1; while(cursor >= 0) {copyb[cursorret] = b[cursor];cursor--;cursorret--;} int p = MaxLen - 1; int sign = 0; while(p >= 0) { int tempa = copya[p] - 48; int tempb = copyb[p] - 48; int sum = tempa + tempb + sign; if(sum == 0) {ret[p] = ‘0‘; sign = 0;} else if(sum == 1) {ret[p] = ‘1‘;sign = 0;} else if(sum == 2) {ret[p] = ‘0‘;sign = 1;} else if(sum == 3) {ret[p] = ‘1‘;sign = 1;} p--; } if(ret[0] == ‘0‘) {ret.erase(0,1);} return ret; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。