-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Description
Question:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Solution:
class Solution {
public:
string addBinary(string a, string b) {
int alen = a.length();
int blen = b.length();
if( alen < blen ){
swap(a, b);
swap(alen, blen);
}
int minus = alen - blen;
if( minus != 0){
while( minus !=0 ){
b = "0" + b ;
minus--;
}
}
string result;
int carry = 0, atem , btem;
int pos = alen - 1;
while( pos >= 0){
atem = a[pos] - '0';
btem = b[pos] - '0';
int sum = atem + btem + carry ;
int res = sum % 2 ;
carry = sum / 2 ;
char re = res + '0';
result = re + result;
pos--;
}
if ( carry == 1)
result = "1" + result;
return result;
}
};