标签:style blog http io ar color sp for strong
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
先进行对齐操作,然后从右往左逐位相加,注意进位即可。
代码写的比较长,但是很简单,就是分00,01,10,11四种情况并考虑进位。
class Solution { public: string addBinary(string a, string b) { if(a == "") return b; else if(b == "") return a; else {//align int size1 = a.size(); int size2 = b.size(); int size = max(size1, size2); if(size1 > size2) { int gap = size1-size2; string space(gap, ‘0‘); b = space+b; } else { int gap = size2-size1; string space(gap,‘0‘); a = space+a; } int tag = false; for(int i = size-1; i > 0; i --) { if(a[i] == ‘0‘ && b[i] == ‘0‘) { if(tag == true) {//carry bit used tag = false; a[i] = ‘1‘; } } else if(a[i] == ‘0‘ && b[i] == ‘1‘) { if(tag == true) //carry bit continues a[i] = ‘0‘; else a[i] = ‘1‘; } else if(a[i] == ‘1‘ && b[i] == ‘0‘) { if(tag == true) //carry bit continues a[i] = ‘0‘; else a[i] = ‘1‘; } else {//‘1‘ add ‘1‘ if(tag == true) //carry bit continues a[i] = ‘1‘; else {//carry bit generates a[i] = ‘0‘; tag = true; } } } //add the first digit if(a[0] == ‘0‘ && b[0] == ‘0‘) { if(tag == true) //carry bit used a[0] = ‘1‘; } else if(a[0] == ‘0‘ && b[0] == ‘1‘) { if(tag == true) {//carry bit continues a[0] = ‘0‘; a = "1"+a; } else a[0] = ‘1‘; } else if(a[0] == ‘1‘ && b[0] == ‘0‘) { if(tag == true) {//carry bit continues a[0] = ‘0‘; a = "1"+a; } else a[0] = ‘1‘; } else {//‘1‘ add ‘1‘ if(tag == true) //carry bit continues a[0] = ‘1‘; else //carry bit generates a[0] = ‘0‘; a = "1"+a; } return a; } } };
标签:style blog http io ar color sp for strong
原文地址:http://www.cnblogs.com/ganganloveu/p/4155014.html