John
John

Reputation: 123

C++- Adding or subtracting '0' from a value

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;
    }
};

Upvotes: 8

Views: 2181

Answers (4)

asam
asam

Reputation: 347

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.

Upvotes: 1

lsalamon
lsalamon

Reputation: 8174

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.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477000

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'.

Upvotes: 4

Pete Becker
Pete Becker

Reputation: 76245

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'.

Upvotes: 10

Related Questions