1. Problem
For a given number n for example (1234), write a Java program to reverse the number (4321 in this case).
2. Steps reverse a number
Here are the steps to reverse a number:
- Initialize a variable to store the reversed number:
- Start with
reversedNumber = 0
.
- Start with
int reversedNumber = 0;
- Extract digits from the original number:
- Use the modulo operator (
%
) to get the last digit of the number. - Add this digit to the reversed number after multiplying the reversed number by 10 (to shift the digits to the left).
- Remove the last digit from the original number by dividing it by 10 (using integer division).
- Use the modulo operator (
while (number != 0) { int digit = number % 10; // Get the last digit reversedNumber = reversedNumber * 10 + digit; // Add the digit to reversedNumber number = number / 10; // Remove the last digit }
- Return the reversed number:
- Once the original number becomes
0
, the reversed number is ready.
- Once the original number becomes
return reversedNumber;
3. Program
public class ReverseNumber { public static int reverse(int number) { int reversedNumber = 0; while (number != 0) { int remainder = number % 10; // Get the last digit reversedNumber = reversedNumber * 10 + remainder; // Add the digit to reversedNumber number /= 10; // Remove the last digit } return reversedNumber; } public static void main(String[] args) { int number = 1234; // Example number to reverse int result = reverse(number); System.out.println("Reversed Number: " + result); // Output: Reversed Number: 4321 } }