Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
注意防止长度不同的,不小心的操作导致溢出。再者插入字符每次是从头开始插入!
string reverse_str(string str)
{
int len = str.size();
int first,last;
char temp;
first = 0;
last = len -1;
while(first <= last)
{
temp = str[first];
str[first] = str[last];
str[last] = temp;
first ++;
last -- ;
}
return str;
}
string addBinary(string a, string b) {
int size = 0;
int carry = 0;
int value = 0;
int x,y;
int len_a,len_b;
string str,str_a,str_b;
str_a = reverse_str(a);//可以用 reverse(a)库函数!#include <algorithm>
str_b = reverse_str(b);
len_a = str_a.size();
len_b = str_b.size();
size = max(len_a,len_b);
for(int i = 0;i < size;i++)
{
if(i < len_a)//溢出!!!!
x = str_a[i] - '0';
else
x = 0;
if(i < len_b)
y = str_b[i] - '0';
else
y = 0;
value = (x+y+carry)%2;
carry = (x+y+carry)/2;
str.insert(0 ,1,value+'0');//每次从开始插入,指明是插入一位
}
if(carry == 1)//最后的判断最高位有进位
str.insert(0, 1,'1');
return str;
}