File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Swaping Numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Swaping Numbers" Watch "Swaping Numbers" New topic

Swaping Numbers

Sam Benry
Ranch Hand

Joined: Mar 21, 2008
Posts: 89
lets say we have
long n = 987654321;

I want to create a loop to make
n = 897654321
n = 879654321
n = 798654321
n = 789654321
n = 698754321
n = 123456789

I'm really confused on how to make this loop, can anyone help me?
I started with the basics, but this is not even close to what i want to make.
Please help, thanks
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
More of a beginner's question.

I am afraid you are right, you are nowhere near.

Try getting the number into an int[] array by using the / and % operators, then work out how to swap a pair of numbers, then work out how to use the swap method to reverse the array, then put the array back into a number.

Hint: I wrote about swapping and reversing arrays about 3 months ago. You will need a swap method and a reverse method which uses swap. Both methods sound good candidates for static methods.
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
As an aside, the best method to convert a number into a String is the String.valueOf method.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
imaya Munusamy

Joined: May 19, 2008
Posts: 20
try this
long n = 987654321;
for(int i=1;i<15;i++)
int j = i % 9;
long f = (long) (n % (Math.pow(10 ,9-j )) * Math.pow(10, j));
long l = (long) (n / (Math.pow(10 ,9-j ))) ;
System.out.println(j + " - " + ( f + l) );
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Welcome to JavaRanch, Imaya Munusamy

You are on the right lines, but I think Sam wants division by 10, not 9.

We have a policy of not simply giving answers to that sort of question, but hints, and I think your post provides a very good hint for Sam Benry to work from.

Please don't post a refinement of that method, Imaya, but Sam, please use that as a start and work out what you are going to do. You will remember it a lot better after working it out for yourself.
I agree. Here's the link:
subject: Swaping Numbers
It's not a secret anymore!