Results 1 to 15 of 15
  1. #1
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Question 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. #2
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    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. #3
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up 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. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    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. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default

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

  6. #6
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default 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. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sonny View Post
    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. #8
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    Nice one, Jos :)
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by PhHein View Post
    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. #10
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up

    Quote Originally Posted by JosAH View Post
    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. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sonny View Post
    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.

    Quote Originally Posted by sonny View Post
    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. #12
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default 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. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sonny View Post
    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. #14
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default

    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. #15
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default

    Quote Originally Posted by JosAH View Post
    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

Similar Threads

  1. reverse a string with a while loop...
    By OptimusPrime in forum New To Java
    Replies: 9
    Last Post: 12-28-2009, 11:06 PM
  2. strings stringbuilders replace and reverse
    By bicepatron in forum New To Java
    Replies: 4
    Last Post: 09-13-2009, 01:17 PM
  3. how do i reverse this method for sorting?Again!
    By PureAwesomeness in forum New To Java
    Replies: 2
    Last Post: 03-09-2009, 12:51 AM
  4. Positive Divisor of int
    By starchildren3317 in forum New To Java
    Replies: 16
    Last Post: 02-20-2009, 03:25 AM
  5. How to reverse two dimensional
    By masaka in forum New To Java
    Replies: 4
    Last Post: 05-19-2008, 10:02 AM

Posting Permissions

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