I am trying to add two numerical char arrays such as:
"124" and "589"
I wrote functions to reverse the string and add the strings, and it works for strings like "123" and "456", but when the last digits are greater than 10, I don't know how to carry it, since the string is in reverse. Here's my code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char* addNum(char* n1, char* n2, int max_size);
void reverseStr(char* str);
bool isEven(int i);
void flipChar(char &ch1, char &ch2);
int main()
{
char *n1, *n2, ch, *res;
int max_size;
cout << "Maximum number of digits: ";
cin >> max_size;
max_size += 2;
n1 = new char[max_size];
n2 = new char[max_size];
while ((ch = cin.get()) != '\n' && ch != -1);
cout << "Enter first number: ";
cin.getline(n1, max_size);
while ((ch = cin.get()) != '\n' && ch != -1);
cout << "Enter second number: ";
cin.getline(n2, max_size);
res = addNum(n1, n2, max_size);
cout << "Result: ";
cout << res;
return 0;
}
char* addNum(char* n1, char* n2, int max_size)
{
int max, greater_len, n, carry, i;
char *res;
carry = 0;
res = new char[max_size + 3];
if (strlen(n1) > strlen(n2))
{
max = strlen(n2);
greater_len = strlen(n1) - strlen(n2);
}
else if (strlen(n1) < strlen(n2))
{
max = strlen(n1);
greater_len = strlen(n2) - strlen(n1);
}
else
{
max = strlen(n1);
greater_len = 0;
}
reverseStr(n1);
reverseStr(n2);
for (i = 0; i < max; i++)
{
n = (n1[i] - '0') + (n2[i] - '0') + carry;
carry = 0;
while (n >= 10)
{
n -= 10;
carry++;
}
res[i] = n + '0';
if ((i == max - 1) && (carry > 0))
{
i++;
res[i] = carry;
}
}
if (greater_len != 0)
{
for (i = max; i < max + greater_len; i++)
{
n = (n1[i] - '0') + (n2[i] - '0') + carry;
carry = 0;
while (n >= 10)
{
n -= 10;
carry++;
}
res[i] = n;
}
}
res[i] = '\0';
reverseStr(res);
return res;
}
void reverseStr(char* str)
{
char *front, *rear, ch;
front = str;
rear = str + strlen(str) - 1;
if (isEven(strlen(str)))
{
while (front != str + ((strlen(str) / 2) - 1))
{
flipChar(*front, *rear);
front++;
rear--;
}
}
else
{
while (front != rear)
{
flipChar(*front, *rear);
front++;
rear--;
}
}
}
bool isEven(int i)
{
if (i % 2 == 0)
return true; //EVEN
return false; //ODD
}
void flipChar(char &ch1, char &ch2)
{
char ch;
ch = ch1;
ch1 = ch2;
ch2 = ch;
}
Thanks