Skip to content
thesarfo

Reference

Reversing a Number

Reversing the digits of a number by extracting the last digit and appending it to a running reversed number.

views 0

We can reuse the digit-extraction algorithm, just that now instead of extracting digits we append them to a reversed number.

Reversing a number

Algorithm:

  1. Initialize an integer revNum to 0. This will store the reversed number.
  2. Iterate while the input integer n is greater than 0.
  3. Calculate the last digit using the modulus operator (n % 10) and store it in lastDigit.
  4. Remove the last digit from the input integer by dividing it by 10.
  5. Update the reversed number: revNum = (revNum * 10) + lastDigit. This appends the last digit to the end of the reversed number.
  6. After exiting the loop, return the reversed number.
public class Main {
public static void reverse(int n) {
// Initialize a variable 'revNum' to
// store the reverse of the input integer.
int revNum = 0;
// Start a while loop to reverse the
// digits of the input integer.
while(n > 0){
// Extract the last digit of
// 'n' and store it in 'ld'.
int ld = n % 10;
// Remove the last digit from 'n'.
n = n / 10;
// Multiply the current reverse number
// by 10 and add the last digit.
revNum = (revNum * 10) + ld;
}
// Print the reversed number.
System.out.println(revNum);
}
}