Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the method reverse (as defined below), which reverses the digit of a gi

ID: 3733046 • Letter: C

Question

Consider the method reverse (as defined below), which reverses the digit of a given
NaturalNumber . For example, if the initial value of n is 346, after it will be 643.
/**
* Reverses the digits in NaturalNumber n.
*
* @updates n
* @requires [none of the digits in n is 0]
* @ensures n = [#n with its digits reversed]
*/
private static void reverse(NaturalNumber n) { … }
1. Implement this method without using recursion. You can only use kernel methods (including
Standard methods), and you are not allowed to use any other reference types besides
NaturalNumber (so no arrays, Strings, etc.).
2. Implement this methods using recursion. You may use non-kernel methods, but you are still
restricted from using any other reference types besides NaturalNumber . You may write additional
“helper” methods that you can call inside your implementation, but they must obey all the same
restrictions above. If you write helper methods, include full JavaDoc contracts for them.

Explanation / Answer

import java.util.Scanner; public class ReverseNumber { private static void reverse(int n) { int rev = 0; while(n != 0) { rev = (rev * 10) + (n % 10); n /= 10; } System.out.println("Reverse number using loop : " + rev); } private static void reverseRecur(int n) { if (n < 10) { System.out.println(n); return; } else { System.out.print(n % 10); reverseRecur(n / 10); } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the natural number : "); int n = scan.nextInt(); reverse(n); System.out.print("Reverse number using recursion : "); reverseRecur(n); } }