'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.

