LeetCode (52): Add Binary
Given two binary strings, return their sum (also a binary string ).
For example,
A ="11"
B ="1"
Return"100"
.
The questions are not complex. The following is my program, followed by other people's programs. It's really easy!
Lengthy !!!!!!!
class Solution {public: string addBinary(string a, string b) { string result; bool more=false; int i,j; for(i=a.size()-1,j=b.size()-1;i>=0 && j>=0;i--,j--) { if(!more) { if(a[i]=='0' && b[j]=='0') { result.push_back('0'); } else if((a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0')) { result.push_back('1'); } else { result.push_back('0'); more=true; } } else { if(a[i]=='0' && b[j]=='0') { result.push_back('1'); more=false; } else if((a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0')) { result.push_back('0'); more=true; } else { result.push_back('1'); more=true; } } } string c=(i>=0?a:b); int k=(i>=0?i:j); for(;k>=0;k--) { if(!more) { result.push_back(c[k]); } else { if(c[k]=='0') { result.push_back('1'); more=false; } else { result.push_back('0'); more=true; } } } if(more) result.push_back('1'); reverse(result.begin(),result.end()); return result; }};
Great God
The auto-incrementing loop is concise and powerful !!!!! Gap
Struct Solution {string addBinary (string a, string B) {if (. size () <B. size () swap (a, B); // save directly in a, no auxiliary space int I =. size (), j = B. size (); while (I --) {if (j) a [I] + = B [-- j] & 1; // '0' & 1 is 0, '1' & 1 is 1 if (a [I]> '1') {// if you need to carry a [I]-= 2; // The carry character if (I)
A [I-1] ++; // carry
else
A = '1' + a; // Add one} return ;}};