Java Program to Reverse a Number

Given below is a Java Program to reverse a number.

public class ReverseNumber {

    public void reverse(int num) {
        int reverse = 0;
        while (num > 0) {
            int rem = num % 10;
            reverse = reverse * 10 + rem;
            num = num / 10;
        }
        System.out.println("The reversed number is " + reverse);
    }
}

The method reverse() accepts an integer and reverses it. We first initialize reverse to zero. In a while loop, we find the remainder on dividing the number by 10. We add this digit to the result by multiplying it with 10 and adding the extracted digit. We then remove the last digit of num by dividing it by 10. When num becomes 0, there will be no more numbers left and we print the answer.

Here is a sample execution :

Input :

num = 347

Output :

The reversed number is 743

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>