C++- Adding or subtracting '0' from a value - 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;
}
};

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.

Related

What is '0' means? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm new to programming and sometimes see expressions like this
...
for (int i=0; i<str1.length(); i++)
{
int sum = ((str1[i]-'0')+(str2[i]-'0'));
str.push_back(sum%10 + '0');
}
...
So that is '0' here? Is it some kind of converting or something?
It's literally the character zero '0'
The operation str[i] - '0' is used to convert the representation of a digit into its numeric value.
Since the characters from '0' to '9' are following in the ascii table, having respectively, the values 48 to 57, when you perform the operation '3' - '0', the interpreter will use the ascii values, 51 - 48 == 3, so you can convert '3' to 3
ASCII Table
(source of the picture : Wikipedia)
'0' is the character zero. Since characters are sequential, adding a digit to 0 will produce the character representing that digit (once cast back to a char). E.g., (char)(2 + '0') (i.e., the integer two plus the character zero) will produce '2' (i.e., the character two).
Well
str2[i] - '0'
Converts character representation of a digit ('3', '7', '9') into its integer value (3, 7, 9). More accurate (and more wordy) construction is
(int)char.GetNumericValue(str2[i])
What is implied, but not really stated, in the other answers is that int and char can be treated as fairly equivalent in c#. You can do math on chars just like you can on ints, and you can convert back and forth between int and char with ease. The number you get is based on the position in the utf8 character tables for the char.
'0' as a char has an int value of 48, so you could do:
int x = 7;
char c = x+48; //c would be '7' as a char, or 55 as an int
Other examples:
char c = 'a';
c++;
Console.Write(c); //prints 'b', because 'a' + 1 is b
It's quite logical and reasonably helpful sometimes* but the main reason you might see '0' is that it's easier to remember '0' than it is to remember 48 (it's slightly easier to remember the hex version 0x30)
All these give you char 5 from int 5:
char five = 5 + 48;
char five = 5 + 0x30;
char five = 5 + '0';
Which one would you find easiest to remember? :)
*for example, say you wanted to count the chars in an ascii string, you could do:
var counts = new int[256];
foreach(char c in string)
counts[c]++;
You can use the char to index the array just like you can an int. At the end of the operation "hello world" would have put a 1 in index 104 (the h), a 3 in index 108(the l) etc..
Sure these days you might use a Dictionary<char, int> but appreciating that intrinsic char/int equivalence and how it can be used has its merits..
What is '0' means?
In C++, it is a character literal.
The fundamental reason why/how str1[i] - '0' works is through promotion.
In particular when you wrote:
str1[i]-'0'
This means
both str1[i] and '0' will be promoted to an int. And so the result will be an int.
Let's looks at some example for more clarifications:
char c1 = 'E';
char c2 = 'F';
int result = c1 + c2;
Here both c1 and c2 will be promoted to an int. And the result will be an int. In particular, c1 will become(promoted to) 69 and c2 will become(promoted to) 70. And so result will be 69 + 70 which is the integer value 139.

Substraction string on string and multiply by int role

I am having issue to understand this code. The goal is to add the sum of all digit from a number until there is only 1 digit recursively
long long superDigit(string n, int k) {
if (n.size() == 1)
return stoi(n);
long long sum = 0;
for (int i = 0 ; i < n.size() ; i++)
sum += (n[i] - '0') * k;
return superDigit(to_string(sum),1);
}
However, i don't understand this line
sum += (n[i] - '0') * k;
n is a string k is an integer what to expect from this kind of multiplication ?
Moreover i tested the operator - on string and i don't get how it works.
Every character has a numerical value. You can find these values on the ASCII Table. The characters 0-9 are placed in a contiguous chunk on the ASCII table, with 0 at 48 and 9 and 57. So, when you do a char minus '0', you get how far away it is from '0' on the ASCII table, effectively converting the character to its corresponding number. '0' - '0' is 0 since they're the same character, '1' - '0' is 1 since 1 is right next to 0 (49 - 48), '2' - '0' is 2 since it's 2 away (50 - 48 = 2), and so on.

What does '0' mean in a subtraction? [duplicate]

This question already has answers here:
C++- Adding or subtracting '0' from a value
(4 answers)
Closed 3 years ago.
class Complex
{
public:
int a,b;
void input(string s)
{
int v1=0;
int i=0;
while(s[i]!='+')
{
v1=v1*10+s[i]-'0'; // <<---------------------------here
i++;
}
while(s[i]==' ' || s[i]=='+'||s[i]=='i')
{
i++;
}
int v2=0;
while(i<s.length())
{
v2=v2*10+s[i]-'0';
i++;
}
a=v1;
b=v2;
}
};
This is a class complex and the function input inputs string and convert it into integers a and b of class complex.
what is the requirement of subtracting '0' in this code
The characters representing the digits, '0' thru '9' have values that are (and must be) sequential. For example, in the ASCII character set the '0' character is encoded with the value 48 (decimal), '1' is 49, '2' is 50 and so on, until '9', which is 57. Other encoding systems may use different actual values for the digits (for example, in EBCDIC, '0' is 240 and '9' is 249), but the C standard requires that they are sequentially congruent. From ยง5.2.1 of the C11 (ISO/IEC 9899:201x) Draft:
In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.
Thus, when you subtract the '0' character from another character that represents a digit, you get the numerical value of that digit (rather than its encoded value).
So, in the code:
int a = '6' - '0';
the value of the a will be 6 (and similarly for other digits).
The reason for not just using a value of (say) 48, rather than writing '0' is that the former would only work on systems that use that particular (i.e. ASCII) character encoding, whereas the latter will work on any compliant system.
"What does '0' means in c++" - The symbol '0' designates a single character (constant) with the value 0, which, when interpreted as an ASCII character (which it will be) has the numerical value 0x30 (or 48 in decimal). So, you are basically just subtracting 48.
I dont quite understand the logic of this function but I hope this will help:
'0' is a character literal for 0 in ASCII. The [] operator of string returns a character. So most likely s[i] - '0' is supposed to get you the digit stored in s[i] as a character. Example: '3' -'0' = 3. Note lack of ' around the 3.
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'.
In this case the goal is to convert the character in the integer digit that represent.

I am not able to understand the concept how string is converted to integers

I referred a program for time conversion and not able to understand some part of the code. Here's the full program.
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.length();
int hh, mm, ss;
hh = (s[0] - '0') * 10 + (s[1] - '0');
mm = (s[3] - '0') * 10 + (s[4] - '0');
ss = (s[6] - '0') * 10 + (s[7] - '0');
if (hh < 12 && s[8] == 'P') hh += 12;
if (hh == 12 && s[8] == 'A') hh = 0;
printf("%02d:%02d:%02d\n", hh, mm, ss);
return 0;
}
The part of code i am not able to understand is
hh = (s[0] - '0') * 10 + (s[1] - '0');
mm = (s[3] - '0') * 10 + (s[4] - '0');
ss = (s[6] - '0') * 10 + (s[7] - '0');
Thanks in advance.
If you see e.g. this ASCII table (ASCII being the most common character encoding scheme) you can see that the character '2' has the decimal value 50, and that the character '0' has the decimal value 48.
Considering that a character is just really a small integer, we can use normal arithmetic on them. That means if you do e.g. '2' - '0' that's the same as doing 50 - 48 which results in the decimal value 2.
So to get the decimal value of a character digit, just subtract '0'.
The multiplication with 10 is because we're dealing with the decimal system, where a number such as 21 is the same as 2 * 10 + 1.
It should be noted that the C++ specification explicitly says that all digits have to be encoded in a contiguous range, so it doesn't matter which encoding is used this will always work.
You might see this "trick" being used to get a decimal value for letters as well, but note that the C++ specification doesn't say anything about that. In fact there are encodings where the range of letters is not contiguous and where this will not work. It's only specified to work on digits.
In the ASCCI encoding numbers are encoded sequentially. This is:
'0' has the value 48
'1' has the value 49
'2' has the value 50
etc
Therefor, 'x' - '0' == x from '0' to '9'
For example:
if you have your string 12:23:53 we have:
hh = (s[0] - '0') * 10 + (s[1] - '0');
(s[0] - '0') means '1'-'0' which is equal to 1, but this is the ten, so *10 + (s[1] - '0') which is '2'-'0', so 2. In total 12.
Same thing for the minutes and seconds.

Is the code below converting a character into its ASCII value?

Is the code below converting a character into its ASCII value?.
I faced a piece of code while studying evaluation of postfix operation,where it says "the expression converts a single digit character in C to its numerical value".?
int x=getch();
int c=x-'0'; /*does c have the ASCII value of x?*/
printf("%d",c);
No, it's converting the ASCII value to a number >= 0.
Let's say you type '1'. getch() will return 49 which is the ASCII value of '1'. 49 - '0' is the same as 49 - 48 (48 being the ASCII value for '0'). Which gives you 1.
Note that this code is broken if you enter a character that is not a number.
E.g. if you type 'r' it will print 'r' - '0' = 114 - 48 = 66
(Ref.)
No, it's giving the numeric value of a digit. So '5' (53 in ASCII) becomes 5.
Is the code below converting a character into its ASCII value?
It isn't. It's doing the opposite (converting an ASCII value to the numerical value) and it only works for decimal digits.
To print the ascii value all you need to do is :
int x=getch();
printf("%d",x);
If you are sure that you only want to accept integers as input then you need to put some constraints to the input before proceeding to process them.
int x = getch();
if (x >='0' || x <= '9') {
int c = x - '0'; // c will have the value of the digit in the range 0-9
. . .
}
Any character(in your case numbers) enclosed within single quotes is compiled to its ASCII value. The following line in the snippet above translates to,
int c=x-'0'; ---> int c= x-48; //48 is the ASCII value of '0'
When the user inputs any character to your program, it gets translated to integer as follow,
If x = '1', ASCII of '1' = 49, so c= 49-48 = 1
If x = '9', ASCII of '9' = 57, so c= 57-48 = 9 and so on.