I am trying to write a program that given two integers in two strings, substracts the second integer from the first integer and outputs it.

1. I read in two strings.
2. I reverse them (I am also adding them, I found it easier to add if they are reversed)
3. I check if any of them are negative...
4. If both are negative or no negatives, I add them up.
5. If any ONE of them is negative, I substract the second string from the first string. <<<< Problem >>>>
6. Store the answer in an integer array.
7. Output the integer array BACKWARDS.


Here is what I have so far for substraction, but it doesn't work for some numbers. It gives weird answers like (-1) + 10000 = 90001.

for (c = 0; c < len; c++)
		{
			// If the first number is bigger, then its simple.
			if((	one[c] > two[c]) || (two[c] == one[c]))
			{
				sum[c] = absolute((one[c] - 48) - (two[c] - 48));
			}
			else if (two[c] > one[c])
			{
				// If not then find it actual value, add ten to it and then substract it.. :)
				sum[c] = absolute(((one[c] + 10) - 48) - (two[c] - 48));
				
				// Then take one away from the next number in 'one'				
				one[c+1] -= 1;
			}
		}

Can someone help me here? I don't get what I am doing wrong...

Recommended Answers

All 9 Replies

I think we need more code to analyze this. If the program is less than about 250 lines, post it with line numbers:

[code=cplusplus] // paste code here

[/code]

That way there's no guesswork. The problem could be in the string-reversal, the negative handling, the absolute value handling, etc. If it's a big program, post a fragment, but a COMPLETE fragment please, so we can run it.

Is there a reason you don't just convert the strings to integers and subtract normally, or is this an assignment where you are supposed to do it digit by digit?

I think we need more code to analyze this. If the program is less than about 250 lines, post it with line numbers:

[code=cplusplus] // paste code here

[/code]

That way there's no guesswork. The problem could be in the string-reversal, the negative handling, the absolute value handling, etc. If it's a big program, post a fragment, but a COMPLETE fragment please, so we can run it.

Is there a reason you don't just convert the strings to integers and subtract normally, or is this an assignment where you are supposed to do it digit by digit?

I am suppose to be able to add numbers upto 100000 digits with negative signs.


Here is what I have so far..

// Make a new substraction function that goes from right to left instead of left to right.
// - start at (len - 1) eg. If (len == 5) then start at 4. If (len == 10) then start at 9
// - make your way left towards zero
// You can't just substract one from the number left to it, you have to make sure that you find a number that is bigger than
// '48'... Then add ten to next number and then continue.....

#include<iostream>
#include<string>
#include<iomanip>
#include<algorithm>
using namespace std;

int absolute(int input) // Takes in a number and returns the absolute value of that number.
{
	if (input >= 0)
	{
		input = input;
	}
	else if (input < 0)
	{
		input = -input;
	}

	return input;
}

int main()
{
	string one, two, pad;
	int len, c, sum[99000], x = 0, temp = 0;
	bool overflow = false, onebig = false, bothequal = false, oneneg = false, twoneg = false, breaking = false;


	// Read in two numbers as a string
	getline(cin, one);
	getline(cin, two);

	// Checks which number is bigger.
	if(one.length() > two.length())
	{
		onebig = true;
	}
	else if (two.length() > one.length())
	{
		onebig = false;
	}
	else
	{
		bothequal = true;
	}


	// Checking if it has any negatives, if it does, it will also erase it.
	if(one[0] == '-')
	{
		oneneg = true;
		// deleting the negative sign
		one.erase(0, 1);
	}
	if(two[0] == '-')
	{
		twoneg = true;
		// deleting the negative sign
		two.erase(0, 1);
	}

	// Reverse the two numbers
	reverse(one.begin(), one.end());
	reverse(two.begin(), two.end());

	// Pad
	if(one.length() > two.length())
	{
		// Append adds things at the END of a string...
		two.append(one.length() - two.length(), '0');
		len = one.length();
	}
	else if (one.length() < two.length())
	{
		one.append(two.length() - one.length(), '0');
		len = two.length();
	}
	else if (one.length() == two.length())
	{
		len = one.length();
	}

	// Initialize the 'sum' array to ZERO
	for(x = 0; x < 99000; x++)
	{
		sum[x] = 0;
	}

	// Main Adding function
	if((oneneg == false && twoneg == false) || (oneneg == true && twoneg == true))
	{
		// Addition function

		for(c = 0; c < len; c++)
		{
			// Find it actual value and sum it up
			sum[c] += (one[c] - 48) + (two[c] - 48);

			if (sum[c] > 9) // Checks if the sum is bigger than or equal to 10. 
			{				// It if it, it reduces it by ten and carries one to the next element in the array 'sum'
				// Substract ten from the number
				sum[c] -= 10;
				// Carry the one to the next element in the final array 'sum'
				sum[c+1] = 1;

				if (c+1 == len)
				{
					overflow = true;
				}
			}
		}
	}
	else if ((oneneg == true && twoneg == false) || (oneneg == false && twoneg == true))
	{
		// Substraction function
		// If any of the numbers are negatives

		for (c = (len - 1); c >= 0; c--)
		{
			if(one[c] < two[c]) // If 'one' is smaller than 'two'
			{
				// Add ten to it and subtract
				sum[c] = absolute(((one[c] - 48) + 10) - (two[c] - 48));

				// Take one away...
				temp = c - 1; // 'temp' created to represent 'c' in the while loop
				while(breaking == false && c != 0)
				{
					if(one[temp] - 48 > 0) // If the number is bigger then substract one from it and break free
					{
						one[temp] -= 1;
						breaking = true;
					}
					else
					{
						if(one[temp] - 48 == 0) // If the number is 0 then make it 9
						{
							one[temp] = 57;
						}
						else // If its not 0 then subtract one from it
						{
							one[temp] -= 1;
						}
					}

					temp--; // reduce 'temp' for the next cycle...
				}
			}
			else if (one[c] > two[c] || one[c] == two[c]) // If 'one' is bigger than 'two'
			{
				sum[c] = ((one[c] - 48) - (two[c] - 48)); // Substract simple way...
			}
		}
	}
/*

		// reverse the strings to bring them back into their true order
		// reverse(one.begin(), one.end());
		// reverse(two.begin(), two.end());

		for (c = 0; c < len; c++)
		{
			// If the first number is bigger, then its simple.
			if((	one[c] > two[c]) || (two[c] == one[c]))
			{
				sum[c] = absolute((one[c] - 48) - (two[c] - 48));
			}
			else if (two[c] > one[c])
			{
				// If not then find it actual value, add ten to it and then substract it.. :)
				sum[c] = absolute(((one[c] + 10) - 48) - (two[c] - 48));
				
				// Then take one away from the next number in 'one'				
				one[c+1] -= 1;
			}
		}



*/

	// OUTPUT
	//cout << "One = " << one << endl << "Two = " << two << endl << "len = " << len << endl << "Sum = ";

	if(overflow == true) // Checks for the overflow and adds one to the 'len' so that
	{					 // when you substact one, it does not make it too short.
		len++;
	}

	if(oneneg == true && twoneg == true) // When two negatives are added, the sum is always a negative number.
	{
		cout << '-'; // outputting the negative sign
	}
	else if(onebig == true && oneneg == true) // Outputs the sign of the bigger number if it is negative. Else it wont output any sign.
	{
		cout << '-';
	}
	else if(bothequal == false && onebig == false && twoneg == true)
	{
		cout << '-';
	}

	for (int i = len-1; i >= 0; i--) // Outputs the 'sum' array
	{
		cout << sum[i];
	}

	return 0;
}

Is there ever an attempt to discern which of the two numbers (one or two) is negative and which is positive in the code below? If you are assuming that one is positive and two is negative in the following code, or if you are assuming that one's absolute value is bigger than two's absolute value in the following code by the time the program reaches this point, I don't see anywhere where you make sure that is the case beforehand.

I would walk through the program with -1 and 2 as input. That gets rid of all for-loops and all length issues, as well as all padding code and reversal code and will help pinpoint the problem. It's a single digit minus a single digit. I think you are making some assumptions regarding one and two when you get to this point in the code and I am not clear what they are, so it's hard for me to follow the logic. I think that you should change your comments so that you don't say "number" if you mean "digit" so it is more clear. I assume a number/digit is "bigger" if its absolute value is bigger (i.e. whether it is negative is irrelevant, perhaps). one is a number. one[0] is a digit. I am guessing that the intent is make both numbers positive, then subtract the one with the smaller absolute value from the one with the larger absolute value, then add a negative sign if needed. But I am not positive that this is what is intended.

else if ((oneneg == true && twoneg == false) || (oneneg == false && twoneg == true))
	{
		// Substraction function
		// If any of the numbers are negatives

		// reverse the strings to bring them back into their true order
		// reverse(one.begin(), one.end());
		// reverse(two.begin(), two.end());


		for (c = 0; c < len; c++)
		{
			// If the first number is bigger, then its simple.
			if((	one[c] > two[c]) || (two[c] == one[c]))
			{
				sum[c] = absolute((one[c] - 48) - (two[c] - 48));
			}
			else if (two[c] > one[c])
			{
				// If not then find it actual value, add ten to it and then substract it.. :)
				sum[c] = absolute(((one[c] + 10) - 48) - (two[c] - 48));
				
				// Then take one away from the next number in 'one'				
				one[c+1] -= 1;
			}
		}
	}

I actually, I understand the adding part but, I don't understand this subtraction part. I tried two different way, and they both failed.

What am I doing wrong??

If everything is wrong, how do you subtract two numbers in strings??

I actually, I understand the adding part but, I don't understand this subtraction part. I tried two different way, and they both failed.

What am I doing wrong??

If everything is wrong, how do you subtract two numbers in strings??

There is more than one way to do it. I am trying to ascertain what you are trying to do and what assumptions you are making. In other words, what the methodology/algorithm is. From that, one can figure out if it is a flawed methodology/algorithm and whether is is making unstated assumptions or not. If the algorithm/methodology is sound and the program is not, then somewhere the code isn't following the algorithm. Since I'm not clear on exactly what the algorithm and assumptions are, I can't tell whether the code complies with them.

Hence my questions from the last post. If you are clear on what the algorithm and assumptions are, please answer them. If you are not clear and are asking for help on developing an algorithm, please say so.

A plus B
Given two positive or negative integers A and B, find their exact sum.

This time there are no limitations on A and B (of course, they will fit in memory).

A or B can be as large as 100 000 digits long.


Is that what you want to know? thats the problem statement.


To do that I developed that program.... I am not sure if there is any better way to do it. If there is, I need help understanding it. If there is not and the way I did it is the best way, I need help in the subtraction part of the program when any ONE of the number is negative.

Thanks once again. :)


EDIT >> I just realized that the only thing that I need to do is make a substraction function for when the second number is bigger than the first one.!!

I did not realize that the current substraction works only if the first number is bigger than the second one...

A plus B
Given two positive or negative integers A and B, find their exact sum.

This time there are no limitations on A and B (of course, they will fit in memory).

A or B can be as large as 100 000 digits long.


Is that what you want to know? thats the problem statement.


To do that I developed that program.... I am not sure if there is any better way to do it. If there is, I need help understanding it. If there is not and the way I did it is the best way, I need help in the subtraction part of the program when any ONE of the number is negative.

Thanks once again. :)

I'm referring to expanding on this algorithm:

1. I read in two strings.
2. I reverse them (I am also adding them, I found it easier to add if they are reversed)
3. I check if any of them are negative...
4. If both are negative or no negatives, I add them up.
5. If any ONE of them is negative, I substract the second string from the first string. <<<< Problem >>>>
6. Store the answer in an integer array.
7. Output the integer array BACKWARDS.

If step 5 is the problem, it needs to be expanded on. A few things that I was looking for in the code didn't appear to be there, so that's why I was asking. Here is how I would expand step 5.

You have two number strings, one and two. Decide which number's absolute value is larger. Make that number one and the other number number two . Swap if needed and keep track of any swaps. With this method, you'll decide whether the final answer is positive or negative right off the bat. The final answer will be negative if:

1) one was originally negative and had a greater absolute value than two, or:
2) two was originally negative and had a greater absolute value than one.

So decide whether the answer will be negative or positive, make the number with the larger absolute value one and the number with the smaller absolute value two . Strip any minus signs so they are both positive.

Subtract number two from number one digit by digit. Digits in one can borrow from the appropriate adjacent one digit as needed.

You are on the right track, I think, and I think you were thinking along those lines, but I believe you were making assumptions about what one and two contained that were not valid. This isn't the only way to do it, but it is a way.

A plus B
Given two positive or negative integers A and B, find their exact sum.

This time there are no limitations on A and B (of course, they will fit in memory).

A or B can be as large as 100 000 digits long.


Is that what you want to know? thats the problem statement.


To do that I developed that program.... I am not sure if there is any better way to do it. If there is, I need help understanding it. If there is not and the way I did it is the best way, I need help in the subtraction part of the program when any ONE of the number is negative.

Thanks once again. :)


EDIT >> I just realized that the only thing that I need to do is make a substraction function for when the second number is bigger than the first one.!!

I did not realize that the current substraction works only if the first number is bigger than the second one...

We may have cross-posted. Yes, You can make a second function or you can swap it so the first number is bigger as I suggested in my last post.

Hey, thanks

After reading your post one after another, I realized an easy way to fix it, I just needed to switch numbers around depending on which number was bigger :):)

Thanks once again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.