Reputation: 11
I need to write a function string add(string a, string b) where a and b are strings representing integers and the function add(a,b) returns a string representing their sum. Strings a and b can have a maximum of 100 characters.
I have tried different ways but failed, here is where I'm standing right now. So I took the 2 strings and I tried adding each digit starting from last. If in the array at [i] it's more than 10, then add 1 to [i-1], and mod it by 10 to get the last digit.
The return is empty:
string add(string a, string b){
int arrA[a.length()];
int arrB[b.length()];
string Res=" ";
//99999999 2222222
if(a.length()>=b.length()){
//i=7
for (int i=b.length();i>=0;i--){
arrA[i] = (int) (a[i]-'0') + (int) (b[i]-'0');
}
for(int i=b.length()-1;i>=1;i--)
Res[i]=arrA[i];
for(int i=a.length()-1;i>=1;i--){
if (arrA[i]>=10){
arrA[i]=arrA[i]%10;
arrA[i-1]=arrA[i-1]+1;}
}
}
else{
for (int i=a.length();i>=0;i--){
arrB[i] = (int) (a[i]-'0') + (int) (b[i]-'0');
}
for(int i=b.length()-1;i>=1;i--)
Res[i]=arrB[i];
for(int i=b.length()-1;i>=1;i--){
if (arrB[i]>=10){
arrB[i]=arrB[i]%10;
arrB[i-1]=arrB[i-1]+1;}
}
}
return Res;
}
Thank you in advance!
Upvotes: 0
Views: 1042
Reputation: 113
string add(string a, string b) {
int c = stoi(a) + stoi(b);
return to_string(c);
}
Upvotes: 0
Reputation: 76523
Think about how you would do this with pencil and paper, then write code to do the same thing.
You have two strings of digits. Start at the right, add the two digits, and if the result overflows, subtract 10 and note that you have a carry. Store the resulting digit. Move one place to the left. Repeat until done. If you run out of digits in one string, just pretend that you've got zeros for the rest of the digits.
Note that each digit in the input is the character representation of the digit. To get the numeric value, subtract '0'
from each digit. Once you have the result, convert it to a character by adding '0'
.
Upvotes: 1