Sunday, November 1, 2009

Program to Reverse the Digits in an Integer

The problem: "Rewrite the "Digit Sum" program given in Figure 4-6 so that instead of adding the digits in the number, it generates the number that has the same digits in the reverse order, as illustrated by this sample run:

'This program reverses the digits in an integer.
Enter a positive integer: 1729
The reversed number is 9271'

The idea in this exercise is not to take the integer apart character by character, which you will not learn how to do until Chapter 8. Instead, you need to use arithmetic to compute the reversed integer as you go. In this example, the new integer will be 9 after the first cycle of the loop, 92 after the second, 927 after the third, and 9271 after the fourth." (Robers ch 4, exercise 6).

Here's my code:



/*
* File: ReverseIntegers.java
* Name: Renee
* Section Leader: Chubacca
* -----------------
*This program follows the insight from the Digital Root problem that the last digit in an integer is the
*same thing as the remainder of that number when divided by 10. We use a while loop to divide the imput
*by 10 repeatedly. Each time, we take the last digit of the integer, house it in the variable "temp",
*and add it to the cumulating variable "reverse." Then when n can't be divided by 10 any more, we print
*the number housed in "reverse."
*/


import acm.program.*;


public class ReverseIntegers extends ConsoleProgram {
public void run() {

println("This program reverses the integers in an integer.");

int n = readInt("Enter a positive integer: ");

//If there's only one digit, print; we're done
if (n <= 9) { println("The reversal is " + n); } else { int temp = 0; int reverse = 0; while (n > 0) {
temp = n % 10;
reverse = 10*reverse + temp;
n/=10;
}
println ("The reverse is " + reverse);
}
}
}








What the output looks like:


What made it tough: This was actually quite easy to figure out, having just worked on the sister problems for digital root and fib sequence. It took about 10 minutes to sketch out. Jason and Annie's examples for fib sequence, which used temp variables, made it easy to think of using temp variables for this problem.

Time to complete: 20 minutes.

9 comments:

  1. I will leave you a purely meta/stylistic comment since you seemed to have no problem with the coding part.

    You should use pre tags for your code! Right now the leading spaces are getting stripped because it's html. If you used pre's, the code would appear properly indented. That would make it way easier for me to read your code.

    ReplyDelete
  2. In Common Lisp:

    http://gist.github.com/246956

    ReplyDelete
  3. in fact, this program will not work fine when the integer is 10 or 1000 or any other like this.

    ReplyDelete
  4. it also doesnt work if you use a number with leading 0's

    ReplyDelete
  5. import acm.program.*;

    // This program asks the user for a number up to "+ELEMENTS" long and returns the digits to the user in a print statement in reverse order.
    public class reverseorder extends ConsoleProgram {

    // Elements in the array "digit"
    private static final int ELEMENTS = 10;

    public void run(){



    int digit[] = new int[ELEMENTS]; // Initializing an array with "+ELEMENTS" as the size.
    int count = 0;
    int index = 0;


    //String type variable is used because using an int would cause leading 0's to be truncated.
    //Because this is being taken in as a string , it will need to be converted to an int using the parseInt method.

    String sVal = readLine("Enter a positive interger value up to "+ELEMENTS +" digits.");


    //Takes the value of sVal and sends it to the .length method to get the number of characters in the sVal variable.
    //This value will be used as the iterator in later loops.
    count =(sVal.length());


    while (count > ELEMENTS) {
    sVal = readLine("Value is too long please enter a number of "+ELEMENTS +" or fewer digits.");
    }

    //This takes the input String value of Sval and passes it to the parseInt method to be converted to an int.
    //This is done so that a count can be established for the amount of numbers in the String variable.

    int val = Integer.parseInt(sVal);



    while(index < count) {
    //The last digit is chopped off and stored in the corresponding index element of the array.
    digit[index] = digittrunc(val);

    //The remaining digits get placed in val and the loop starts over using the new val.
    val = digitreturn(val);
    index ++;

    }



    print("The reverse order of " +sVal +" is ");
    for (int i = 0;i < count; i++){
    print(+digit[i]);
    }

    }


    // Everything after this point is a method.


    // This method returns everything except the last digit of the current int val.
    private int digitreturn(int c) {

    int dReturn = c /10;
    return dReturn;
    }

    //This method returns the last digit of the current int val.

    private int digittrunc(int c){

    int dTrunc = c % 10;
    return dTrunc;
    }




    }

    ReplyDelete
  6. Hey! It seems as though we both have a interest for the same thing.

    Your blog, "Blogger: the "How Can Renee Make This Code
    Better?" blog" and mine are very similar. Have you ever thought about authoring a guest write-up for a related blog?
    It will unquestionably help gain exposure to
    your website (my site recieves a lot of targeted
    traffic). If you might be interested, e-mail me at: katherin_oates@gmail.
    com. Appreciate it

    Feel free to surf to my web-site; memory stick sony

    ReplyDelete
  7. Luckily, fleshlight there are
    still some limitations without Flash. According to a patent filing that went
    public just weeks ago, listing co-founder and CEO Mark Zuckerberg as
    a child, we decided to transfer all three.

    ReplyDelete
  8. The creation of the variable temp is not really necessary here. The algorithm would work just fine if you only use:

    while (n > 0) {
    reverse = (reverse * 10) + (n % 10);
    n /= 10; //deletes the last digit
    }

    ReplyDelete