Reverse of a number using java. Java program to reverse of a number.

Reverse of a number in java

In this article you will learn how to reverse a number using java .In different approach . 

Approach :-1    ( Using for loop) 

public class Reverse {
    public static void main(String[] args) {
        int num=1234,rev=0;
        for (int i=0;num>0;i++){
            int lastdigit=num%10;
            rev=rev*10+lastdigit;
            num=num/10;
        }
        System.out.println("The reverse number is "+rev);
    }
}

Output:-  

The reverse number is 4321

Explanation :-


Step-1)First, the remander of the num divided by 10 is stored in the variable lastdigit. Now, the digit contains the last digit of num, i.e. 4. Step-2)Digit is then added to the variable reversed after multiplying it by 10. Multiplication by 10 adds a new place in the reversed number. One-th place multiplied by 10 gives you tenth place, tenth gives you hundredth, and so on. In this case, reversed contains 0 * 10 + 4 = 4. num is then divided by 10 so that now it only contains the first three digits: 123. After second iteration, digit equals 3, reversed equals 4 * 10 + 3 = 43 and num = 12 After third iteration, digit equals 2, reversed equals 43 * 10 + 2 = 432 and num = 1 After fourth iteration, digit equals 1, reversed equals 432 * 10 + 1 = 4321 and num = 0 Now num = 0, so the test expression num != 0 fails and while loop exits. reversed already contains the reversed number 4321. 

Approach :-2        ( Using while loop)

public class Reverse {
    public static void main(String[] args) {
        int num=1234,rev=0,i=1;
        while (num>0){
            int lastdigit=num%10;
            rev=rev*10+lastdigit;
            num=num/10;
            i++;
        }
        System.out.println("The reverse number is "+rev);
    }
}

Output:-
The reverse number is 4321

0 K comment

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel