# Thread: Help with syntax to reverse a positive integer

1. ## Help with syntax to reverse a positive integer

I am new to java.
I am learning with a book and on line videos.

an assignment i am trying to complete requires me to read in a positive integer and to print out the integer in reverse
heres what I have so far
thanks in advance for any help hints or suggestions :)

Java Code:
```/*
* File: ReverseDigits.java
* -------------------
* Programming exercise 7 from Page 97 (Chapter 4)
* The Art and Science of Java by Eric S. Roberts
*
*/
import acm.program.*;
public class ReverseDigits extends ConsoleProgram {

public void run() {
println("This program reverses the digits in an integer.");
int n = readInt("Enter a positive integer: ");
int nReversed = 0;
int digits = 0;
int countdown = n;		// ive duplicated (int n) cos i need (int n) again later
while (countdown > 0) { // this while loop counts the digits in (int n)
countdown /= 10;
digits++;
}
/*
* what i had in mind to do next was a for loop repeated the same amount
* of times as there are digits in (int n)
* then use n % 10 to get the last digit in its own
* if int n was lets say 1234
* I could say that (4E+3) plus (3E+2) plus (2E+1) plus (1E+0) would give me 4321
*/
int Eplus = digits;
for (int i = 0;i<digits;i++){
Eplus--;
nReversed += n%10;// how do i do this bit // nReversed += (n%10)E+(Eplus)
n/=10;
}
println("The reverse of the digits is " + nReversed);
}
}```

2. Member
Join Date
Feb 2010
Posts
29
Rep Power
0
In your code, nReversed will be 10 (4+3+2+1).
You need to multiply each digit by the corresponding multiple of 10. In this case, you can use Math.pow() for instance :

Java Code:
```for (int i = 0;i<digits;i++){
nReversed += n%10[COLOR="Red"][B]*(Math.pow(10, Eplus-1))[/B][/COLOR];
Eplus--;
n/=10;
}```

3. ## Many Thanks,, problem solved

Many thanks, for your help, brilliant, works great :)

I couldnt work out why you used Eplus-1 but then i realised you moved the Eplus--; below the nReversed bit where as i had it above.

you would think that they might have mentioned Math.pow
before setting the task eh!
All they have mentioned so far is scientific notation with the E+ which is why i was going along that way. I had tried assigning nReverse as a double, casting it as a double and using all manner of parenth variations trying to get the syntax to work.

I saw Math.pow while I was looking round but i thought i would have to import some math library to use it (we're only using console program at the moment)

4. heck,
Java Code:
```      String forwardString = Integer.toString(n);

for (int i = 0; i < forwardString.length(); i++) {
System.out.print(forwardString.charAt(forwardString.length() - i - 1));
}```

5. Java Code:
`System.out.println(new StringBuffer(String.valueOf(n)).reverse());`
;)

6. ## More thanks, gee you guys here are so helpful!

thanks Fubarable, and Darryl,
I shall endeavour to play with those bits of code and see what it does,
The math pow was what i was aiming for, we haven't done anything with strings as yet.
Gee you guys in here are so helpful, thanks very much.

7. Originally Posted by sonny
thanks Fubarable, and Darryl,
I shall endeavour to play with those bits of code and see what it does,
The math pow was what i was aiming for, we haven't done anything with strings as yet.
Gee you guys in here are so helpful, thanks very much.
While you're at it, consider this simple recursive solution:

Java Code:
```private static int reverse(int n, int r) {
if (n == 0) return r;
return reverse(n/10, 10*r+n%10);
}
public static int reverse(int n) {
return reverse(n, 0);
}```
It doesn't use Strings nor Math.pow or whatever; all you need to do is call it with one parameters: reverse(number)

kind regards,

Jos

8. Nice one, Jos :)

9. Originally Posted by PhHein
Nice one, Jos :)
Cute eh? Most of the time people forget (me included) that you can use additional parameters for all sorts of purposes while in the middle of recursive calls; e.g. you can pass entire Lists to collect intermediate results or whatever; it greatly simplifies recursion and the used data structures.

kind regards,

Jos

10. Originally Posted by JosAH
Java Code:
```private static int reverse(int n, int r) {
if (n == 0) return r;
return reverse(n/10, 10*r+n%10);
}
public static int reverse(int n) {
return reverse(n, 0);
}```
Thanks Jos
That looks really simple although I hasten to add I'm not that sure exactly what it is doing however the maths bits look familiar.
some questions I have:
Why is there is a public and a private method both called reverse; when it is called how does it know which one to execute?
also where did (int r) come from?

the return command is something I have not yet encountered and using static int to me means using a constant. Do please excuse my ignorance but if you could outline what is happening in simple English (my dutch is worse than my Java :) ) I should be most grateful

kind regards
Sonny

11. Originally Posted by sonny
Why is there is a public and a private method both called reverse; when it is called how does it know which one to execute?
also where did (int r) come from?
The first method is private because I don't want anyone in the outside world to call this method; it only makes sense if it's called with the second parameter equal to zero. Nothing can garantee that so I made a second method (that can be called by everyone) that takes care of it.

Originally Posted by sonny
the return command is something I have not yet encountered and using static int to me means using a constant. Do please excuse my ignorance but if you could outline what is happening in simple English (my dutch is worse than my Java :) ) I should be most grateful
Please start reading Sun's Java Tutorial, you'll be glad you studied it afterwards. That 'return' business is an essential part of Java; you'll cripple the language without it and there is no hocus pocus hidden in it.

kind regards,

Jos

12. ## study, study, study

I will look at that tutorial
I am currently following Stanford University's "CS106a Programming Methodology" course on YouTube, together with the course text book The Art and Science of Java by Eric S. Roberts, I'm using Eclipse cos Stanford provide it on course web site together all the course handouts.

I have just finished Lecture 5 and chapter 4 in the text

Thanks again Jos, I've stuck that code into eclipse and saved with some of my other study tasks. and i'll come back to it when ive progressed some more.:)

kind regards
Sonny

13. Originally Posted by sonny
I will look at that tutorial
I am currently following Stanford University's "CS106a Programming Methodology" course on YouTube, together with the course text book The Art and Science of Java by Eric S. Roberts, I'm using Eclipse cos Stanford provide it on course web site together all the course handouts.

I have just finished Lecture 5 and chapter 4 in the text

Thanks again Jos, I've stuck that code into eclipse and saved with some of my other study tasks. and i'll come back to it when ive progressed some more.:)
Yep, keep it for later and in the mean time play with Karel the Robot ;-) That Stanford course seems like fun (I just watched (part of) a few editions). The course starts off a bit slower than the tutorials but both are good study material; have fun.

kind regards,

Jos

14. Okay im up to the chapter and lecture on methods, despite there being a lot of confusion going on in my head i think i have figured this out.:D
Java Code:
```private static int reverse(int n, int r) {
if (n == 0) return r;
return reverse(n/10, 10*r+n%10);
}
public static int reverse(int n) {
return reverse(n, 0);
}```
public static int reverse is called because (like my program) that has the variable (int n or 1234)
the public method returns two variable to the private method 1234, 0
if (n == 0) return r;
this bit is like a stop now im done and the answer is r and only one variable is returned

return reverse(n/10, 10*r+n%10) returns two variables to the private
1234/10=123 ,,,,, 10*0+n%10=4
then it goes again to the private

123/10=12 ,,, 10*4 + n%10 = 43
and again
12/10=1 ,,, 10*43 + n%10 = 432
until n==0 and r is the answer

jos that is genius

15. Originally Posted by JosAH
Cute eh? Most of the time people forget (me included) that you can use additional parameters for all sorts of purposes while in the middle of recursive calls; e.g. you can pass entire Lists to collect intermediate results or whatever; it greatly simplifies recursion and the used data structures.

kind regards,

Jos
Rather than pass a List to be appended to, I prefer having the recursive method return a List and using addAll(...) to consolidate the results in one List. That way, the external caller doesn't have to pass in a List to begin with. Of course, there could be a public method that calls the (private) recursive method with an appropriate List, but that just adds one more method.

Could you possibly expound on the advantages of passing the List over this approach? Thanks.

My approach can be seen in many of the methods of this class:
Swing Utils « Java Tips Weblog

db

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•