I also use two bool variables to express each digit, which seems not to be a good choice since the logics part looks a little complex.
Logics:
input_carry input_a input_b output_result output_carry
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class Solution { public: string addBinary(string a, string b) { string result; bool signal=false; //for(int i=0; i<a.size() || i<b.size(); i++){ int i; int j; for(i=a.size()-1, j=b.size()-1; i>=0 || j>=0; i--, j--){ bool dig_a=(i<0)?0:(a[i]-'0'); bool dig_b=(j<0)?0:(b[j]-'0'); bool dig_r; if(signal == false){ dig_r=dig_a||dig_b; if(dig_a==1 && dig_b==1) { dig_r=0; signal=true; } } else{ dig_r=dig_a&&dig_b; if(dig_a==0 && dig_b==0){ dig_r=1; signal=false; } } char res=dig_r+'0'; result.insert(0,1,res); } if(signal) result.insert(0,1,'1'); return result; } }; |
From article in reference, use int to express 1 or 0 in each digit, the result and carry could be got by % and /. Below are codes from 水中的鱼.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public: string addBinary(string a, string b) { int carry =0; string result; for(int i = a.size()-1, j = b.size()-1; i >=0 || j>=0; --i,--j) { int ai = i>=0? a[i]-'0':0; int bj = j>=0? b[j]-'0':0; int val = (ai+bj+carry)%2; carry = (ai+bj+carry) /2; result.insert(result.begin(), val+'0'); } if(carry ==1) { result.insert(result.begin(), '1'); } return result; } }; |
More concise and efficient. Awesome! Maybe try later.
reference: http://fisherlei.blogspot.com/2013/01/leetcode-add-binary.html
没有评论:
发表评论