Try the fastest way to create flashcards
Question

(Display an integer reversed) Write a method with the following header to ­display an integer in reverse order:

public static void reverse(int number)

For example, reverse(3456) displays 6543 . Write a test program that prompts the user to enter an integer then displays its reversal.

Solution

Verified
Answered 2 years ago
Answered 2 years ago
Step 1
1 of 3

To reverse a number we first initialize rev. We then add last digit from number to rev and remove that digit from number. We then multiply rev with 10 to add 0 at the end. We repeat the process until number reaches 0.

public static int reverse(int number){
  // Initialize rev
  int rev = 0;
  // Repeat while number is greater than 0
  while(number > 0){
    // Add 0 to the end of rev
    rev *= 10;
    // Add last digit from number
    rev += number % 10;
    // Remove last digit in number
    number /= 10;
  }
  // Return rev
  return rev;
}

Create a free account to view solutions

Create a free account to view solutions

Recommended textbook solutions

Intro to Java Programming, Comprehensive Version 10th Edition by Y. Daniel Liang

Intro to Java Programming, Comprehensive Version

10th EditionISBN: 9780133761313Y. Daniel Liang
1,628 solutions
Fundamentals of Database Systems 7th Edition by Ramez Elmasri, Shamkant B. Navathe

Fundamentals of Database Systems

7th EditionISBN: 9780133970777Ramez Elmasri, Shamkant B. Navathe
961 solutions
Introduction to Algorithms 3rd Edition by Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen

Introduction to Algorithms

3rd EditionISBN: 9780262033848Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen
872 solutions
Introduction to Algorithms 4th Edition by Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen

Introduction to Algorithms

4th EditionISBN: 9780262046305Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen
945 solutions

More related questions

1/4

1/7