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!