I don't understand the process converting string to int [duplicate] - c++

This question already has answers here:
Why does subtracting '0' in C result in the number that the char is representing?
(8 answers)
Closed 1 year ago.
Given the following code.
this problem is Leet Code 415.
string addStrings(string num1, string num2) {
string res;
int sum = 0;
int i = num1.size() - 1;
int j = num2.size() - 1;
while(i >= 0 && j >= 0)
{
sum += (num1[i--] - '0') + (num2[j--] - '0'); // this problem point
res.push_back(char(sum%10 + '0'));
sum = sum/10;
}
while(i >= 0)
{
sum += (num1[i--] - '0');
res.push_back(char(sum%10 + '0'));
sum = sum/10;
}
while(j >= 0)
{
sum += (num2[j--] - '0');
res.push_back(char(sum%10 + '0'));
sum = sum/10;
}
if(sum > 0)
res.push_back(char(sum%10 + '0'));
reverse(res.begin(), res.end());
return res;
}
I don't understand the process converting string to int.
Why is it a int when I subtract '0' from string?
If it doesn't change int, how is it possible to operate on strings?

In c++ characters can be implicitly cast to integers using their ASCII codes. I don't really want to spoil the fun of solving the given problem so i'll just provide a hint here:
Given a single digit number '2' and '4' with an ASCII code of 50 and 52 (decimal) respectively, subtracting '0' with an ASCII code of 48 from both numbers, you get the actual numerical values of the characters (50-48 = 2) and so on.
Have fun coding!

So the way ascii works is that consecutive numbers are following each other. If a string of characters only contain digits, you can get those digits by subtracting the value '0' from them. In ascii '0' = 0x30, '1' = 0x31 etc..
In your code num[i--] - '0' just checks "how far" you are from '0' in the ascii table, giving the correct digit if it is indeed a digit.
Also you don't convert string to anything (at least on the specific line). You access an element, which is a char that is an integer type in c++.

Related

Why is there a need to add a '0' to indexes in order to access array values? [duplicate]

This question already has answers here:
What's the real use of using n[c-'0']?
(13 answers)
Closed 2 years ago.
I am confused with this line:
sum += a[s[i] - '0'];
To give some context, this is the rest of the code:
#include <iostream>
using namespace std;
int main() {
int a[5];
for (int i = 1; i <= 4; i++)
cin >> a[i];
string s;
cin >> s;
int sum = 0;
for (int i = 0; i < s.size(); i++)
sum += a[s[i] - '0'];
cout << sum << endl;
return 0;
}
- '0' (or less portable - 48, for ASCII only) is used to manually convert numerical characters to integers through their decimal codes, C++ (and C) guarantees consecutive digits in all encodings.
In EBCDIC, for example, the codes range from 240 for '0' to 249 for '9', this will work fine with - '0', but will fail with - 48). For this reason alone it's best to always use the - '0' notation like you do.
For an ASCII example, if '1''s ASCII code is 49 and '0''s ASCII code is 48, 49 - 48 = 1, or in the recommended format '1' - '0' = 1.
So, as you probably figured out by now, you can convert all the 10 digits from characters using this simple arithmetic, just subtracting '0' and in the other direction you can convert all digits to it's character encoding by adding '0'.
Beyond that there are some other issues in the code:
The array does not start being populated at index 0, but at index 1, so if your string input is, for instance, "10" the sum will be a[1] + a[0], but a[0] has no assigned value, so the behaviour is undefined, you need to wach out for these cases.
for (int i = 0; i < 5; i ++)
cin >> a[i];
would be more appropriate, indexes from 0 to 4, since the array has 5 indexes, if you want input numbers from 1 to 5, you can subract 1 from the to the index later on.
As pointed out in the comment section, a bad input, with alpabetic characters, for instance, will also invoke undefined behaviour.
From the C++ Standard (2.3 Character sets)
... 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.
So if you have a character for example '4' then to get value 4 you can write '4' - '0'.
If you will write like for example
sum += a[s[i]];
where i is the character '0' then in fact you will have either
sum += a[s[48]];
if the ASCII coding is used or
sum += a[s[240]];
if the EBCDIC coding is used.
The reversed operation of getting a character from a digit you can write for example
int digit = 4;
char c = digit + '0';
Pay attention to that indices of arrays in C++ start from 0.
Thus this loop
for (int i = 1; i <= 4; i ++)
cin >> a[i];
should be written like
for (int i = 0; i < 5; i ++)
cin >> a[i];
Also to avoid such an error you could use the range based for loop like
for ( auto &item : a ) std::cin >> item;

Logical error-encrypting a message in C++

the code should count each character. If the character is a number, it should count the previous character as much as the number.
So if the input is 'a', it should count 'a' once and assign it to acounter which now is equal to 1.
but if after 'a' is 3, it means 'aaa' and it should count 'a' three times and assign it to acounter which now is equal to 3.
Note: the program is for all of the alphabets but if this one isn't solved then what's the point of writing the rest?
I've tried put another loop exclusively for numbers but it didn't work.
char secret_message[1000];
int counter,number_counter;
int acounter=0;
gets(secret_message);
for (counter = 0 ; secret_message[counter] != NULL ; counter++)
{
if (secret_message[counter]=='a')
acounter++;
if (secret_message[counter] >= '0' && secret_message[counter] <= '9')
{
for(number_counter=1;number_counter<=secret_message[counter];number_counter++)
{
if (secret_message[counter-1]=='a')
acounter++;
}
}
}
cout<<endl<<"acounter is:"<<acounter;
if the input is a3 the output should be 3, but it's 52 !
You'll want to convert the digit from text to number, then use addition:
if (isdigit(secret_message[counter]))
{
const int value = secret_message[counter] - '0';
acounter += value;
}

Finding the sum of digits in c++. Different method

I am new to c++ and having trouble with a simple programme
I need to find the sum of digits I can do that in python but I don't know how to do the same in c++.
digits = "1234"
sum = 0
for digit in digits:
sum += int(digit)
print(sum)
How to do the same in c++?
I tried to do the same in c++ but ends up in a error.
string digits = "1234";
int sum, i;
for(i=0;i<digits.length();i++){
sum += stoi(digits[i]);
}
But this doesn't work
string digits = "1234";
int sum = 0;
for(int i = 0; i < digits.length(); i++){
sum += digits[i] - '0';
}
Characters have their numbers (ord). By working with characters in C++ you actually work with these numbers (so char is an integer type). For '0' it's some number, for '1' it's 1 + '0', for '2' it's 2 + '0' and so on. So by subtracting '0' you get the right digit.

Use of s[i] - '0' [duplicate]

This question already has answers here:
How do you convert char numbers to decimal and back or convert ASCII 'A'-'Z'/'a'-'z' to letter offsets 0 for 'A'/'a' ...?
(4 answers)
Closed 7 years ago.
The following code basically takes a string and converts it into an integer value. What I don't understand is why the int digit = s[i] - '0'; is necessary. Why can't it work by using int digit = s[i] instead? What purpose does the -'0' have?
int main(){
string s = "123";
int answer = 0;
bool is_negative = false;
if (s[0] == '-')
{
is_negative = true;
}
int result = 0;
for (int i = s[0] == '-' ? 1 : 0; i < s.size(); ++i)
{
int digit = s[i] - '0';
result = result * 10 + digit;
}
answer = is_negative ? -result : result;
cout << answer << endl;
system("pause");
}
Firstly, in your question title
the use of '0'
should be written as
the use of s[i] - '0'
That said, by subtracting the ASCII value of char 0 (represented as '0'), we get the int value of the digit represented in char format (ASCII value, mostly.)
It's because the value inside s[i] is a char type.
To convert the char '1' into an integer, you do '1' - '0' to get 1. This is determined by position in the ASCII table, char '0' is 48, while char '1' is 49.
The reason for the subtraction is that s[i] is, for example, '6'. The value '6' evaluates to 54 (the ascii code). The ASCII code of '0' is 48. So '6' - '0' = 6, which is the char value expressed as an int.

Put integer in to string using push_back

I am trying to put an integer in to string using the following code:
int x = 42;
string num;
bool negative = false;
if(x < 0)
{
negative = true;
x = x * -1;
}
while(x > 0)
{
num.push_back(x % 10);
x = x / 10;
}
But when I try to output the string, it comes up with the wired character. Could you please help what's happening in this code??
Edited:
ps. I want to do this in kind manual way. Means I don't want to use to_string
There would be weird characters, because when you push_back(), the integer is converted (or rather interpreted) into its corresponding ASCII character, and then pushed back into the string.
The way forward is to convert the integer to a character by adding a '0' to the integer value.
while(x > 0)
{
num.push_back((x % 10) + '0'); //Adding '0' converts the number into
//its corresponding ASCII value.
x = x / 10;
}
The reason to add a '0' to the integer?
The ASCII value of 0 is 48, 1 is 49, 2 is 50 and so on... Hence, what we basically do here is to add 48 (The ASCII value of 0) to the corresponding integer to make it equal to its ASCII equivalent. Incidentally, '0' is equal to 48 because it is the ASCII value of the 0 character.
Use std::to_string with string::append:
while (x > 0)
{
num.append(std::to_string(x % 10));
x = x / 10;
}
using push_back forces you to do more work.
To convert the integer you can use:
Character manipulation: shifting/adding the ASCII representation by '0', thereby making anint value into char value.
Type casting new_type(old_type), there are some additional types of casting.
To expand the length of a string you can use:
String member functions like: push_back(value), append(append).
Concatenation operator like: str += value;
A possible implementation is:
while(x > 0)
{
num+=((x % 10) + '0');
x = x / 10;
}