标签:c style class blog code java
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; } };
leetcode -- Add Binary,布布扣,bubuko.com
标签:c style class blog code java
原文地址:http://www.cnblogs.com/berkeleysong/p/3756816.html