Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
    }
};
like image 673
John Avatar asked Jun 07 '16 15:06

John


People also ask

What does -' 0 do in C?

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

Why you can subtract 0 from a character and have it convert to the numerical value?

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.

Can you add and subtract chars in C?

Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings.


4 Answers

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

like image 189
Pete Becker Avatar answered Oct 04 '22 18:10

Pete Becker


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

like image 20
Kerrek SB Avatar answered Oct 04 '22 17:10

Kerrek SB


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.

like image 25
lsalamon Avatar answered Oct 04 '22 18:10

lsalamon


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.

like image 41
asam Avatar answered Oct 04 '22 19:10

asam