I was searching for a solution to adding two binary strings. My test data for proving the addition:
10 + 1 => 11
1001 + 1 => 1010
1101 + 100 => 10001
10101010 + 11001100 => 101110110
This was the code I've found by googling:
public static string AddBinary(string a, string b)
{
string result = "";
// Initialize digit sum
int s = 0;
// Traverse both strings starting from last characters
int i = a.Length - 1;
int j = b.Length - 1;
while (i >= 0 || j >= 0 || s == 1)
{
// Compute sum of last digits and carry
s += (i >= 0 ? a[i] - '0' : 0); // if i > 0
s += (j >= 0 ? b[j] - '0' : 0);
// If current digit sum is 1 or 3, add 1 to result
result = (char)(s % 2 + '0') + result;
// Compute carry
s /= 2;
// Move to next digits
i--;
j--;
}
return result;
}
Could someone please explain to me what these three lines of code are actually doing here?
s+= (i >= 0 ? a[i] - '0' : 0);
s+= (j >= 0 ? b[j] - '0' : 0);
result = (char)(s % 2 + '0') + result;
I've never used a char
with a plus/minus operator before and not sure what these lines are achieving.
Footnote - the binary calculation looks to be correct