I was looking at the code below and I got the logic but I cannot seem to understand what is the use of '0'
.
class Solution
{
public:
string addBinary(string a, string b)
{
string s = "";
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0': 0;
s = char(c % 2 + '0') + s;
c /= 2;
}
return s;
}
};
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing In C language it is generally used to mark an end of a string.
All of the digit characters have values offset from the value of '0' . That means, if you have a character, let's say '9' and subtract '0' from it, you get the "distance" between the value of '9' and the value of '0' in the execution character set.
Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings.
The C and C++ standards require that the characters '0'..'9'
be contiguous and increasing. So to convert one of those characters to the digit that it represents you subtract '0'
and to convert a digit to the character that represents it you add '0'
.
C++ requires ([lex.charset]/3) that, in the basic character set, the numerals '0'
, '1'
, '2'
, ..., '9'
are encoded as contiguous values. That means that given a numeral character c
, you can compute its integral value as the expression c - '0'
.
The value '0' represent offset of ascii table for numeric character representation. To compare two values when one is ascii and another is binary you need to convert to same base representation.
In ASCII code character 0, represented as '0' in C (and many other languages) has the value 48. Also in ASCII the other 9 numerals are contiguous: '0', '1', etc. A string is composed of characters. So if you subtract '0' to another numeral you get its numeric value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With