Reverse a negative number!!

Hello, so in my computer science class we have been asked to write a good that reverses a number. I can get it to work for positive numbers, but not negative numbers, can you please help? Thanks.

here is my the function i am working on:


int reverseInt(int orig)
{
int rev = 0; // declare a variable for the reversed version
// and initialize it to 0

while (orig > 0) {

int curDig = orig % 10; // create a variable for the current digit,
// and initialize it to orig % 10

rev = (rev * 10 + curDig); // the new value for reversed is
// the old value * 10, plus the new digit

orig = (orig / 10); // drop the digit off of the original
// using orig = orig / 10
}
return rev; // return the reversed value


/*This is what my teacher wants us to do for the negative numbers:*/

// create a boolean variable for isNegative,
// initialized to false
// if the original is less than zero
// set isNegative to true
// and multiply the original by -1

// then have your while loop as per the previous stage

// afterwards, if isNegative is true,
// multiply the reversed value by -1

// afterwards have your normal return statement

/*And this is what i have attempted to do*/
bool isNegative = false;

if (orig < 0){
isNegative = true;
orig * (-1);
}

while (orig > 0){

int curDig = orig % 10;

rev = (rev *10 +curDig);

orig = (orig / 10);

}
if (isNegative = true){
rev = rev * (-1);
return rev;
}

}
what do you think this line does ?
orig * (-1);

your checking if isNegative = true but your not showing us where you get the value for rev.

isn't it switching the orig to a positive number? Since the line before says
if (orig < 0){
isNegative = true;
orig * (-1);

so it is taking a negative value and making it positive?

Also i put the value for rev = 0; at the top of my code and then assigning it:
rev = (rev * 10 + curDig); // the new value for reversed is
add cout to your code and see what you get.

1
2
3
4
5
if (orig < 0){
isNegative = true;
orig * (-1);
cout << orig;
}
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

int main()
{
	int input = 0, output = 0;
       bool isNegative = false;

	cout << "Enter a number: ";
	cin >> input;

	if (input < 0)
	{
		isNegative = true;
		input *= -1;
	}

	while (input != 0)
	{
		output = output * 10 + (input % 10);
		input /= 10;
	}

	if (isNegative)
		output *= -1;

	cout << "Output: " << output << endl;

}
Last edited on
It worked, Thankyou for your help!
Topic archived. No new replies allowed.