vipwoody Posted January 21, 2009 Share Posted January 21, 2009 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 More sharing options...
0 Bookieass Posted January 22, 2009 Share Posted January 22, 2009 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 + 5As 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 More sharing options...
0 Mr. Bean Posted January 22, 2009 Share Posted January 22, 2009 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 More sharing options...
0 vipwoody Posted January 22, 2009 Author Share Posted January 22, 2009 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 More sharing options...
0 Bookieass Posted January 22, 2009 Share Posted January 22, 2009 or u can create a recursive function....... just to find the lenght of the number and store each number in dynamic array Link to comment Share on other sites More sharing options...
0 vipwoody Posted January 22, 2009 Author Share Posted January 22, 2009 yep, i can add that. But since im sure that my application only needs 5 integers, then there is no need for that. Link to comment Share on other sites More sharing options...
Question
vipwoody
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