Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swaping Numbers

 
Sam Benry
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 49432
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an aside, the best method to convert a number into a String is the String.valueOf method.
 
imaya Munusamy
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 49432
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic