• 0

[JAVA] Reversing a number using Integer Operators only


Question

Hello, I just want to know if there is a way you can use the Integer Operators to reverse a number for example: 12345 to 54321 without changing it to a string and applying the reverse function?

Thank you.

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

Seems to me it can be worked out......

Wht we can do is first find out the length of the number.

Then distribute the number into smaller number like

1. In your case, units, tens, hundred, thousand and ten Thousand

3. Store them each in separate int variables. and reverse the process before u add them again

eg:

12345 = 10000 + 2000 + 300 + 40 + 5

As we know the length of the number, we can reverse the order by multiplying the units digit with length (in this case 4) ie increasing from right to left of digit.

Sum up all these individuals to get reverse of a number

Hope it helps

Link to comment
Share on other sites

  • 0

I did this in C# but you should be able to port it to Java very easily:

int Reverse(int input)
{
	bool isNeg = input < 0;
	int result = 0;
	input = isNeg ? input * -1 : input;

	while (input % 10 > 0)
	{				
		result = (result * 10) + (input % 10);
		input /= 10;
	}

	return isNeg ? result * -1 : result;
}

Link to comment
Share on other sites

  • 0

Thank you

I used this:

		int Number = d1;

			int Q1 = Number/10;
			int R1 = Number%10;
			Print (R1);
			Number = Q1;

I repeated the same calculations for 5 times, since the max number of integers that can be input is 5.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.