Latest :

Reverse A Number In Java – 4 Simple Ways | Programs

Reverse A Number In Java – We have discussed the various methods to reverse a number in Java program. To each and every program, compiler is added to execute the program. Along with it, sample outputs are also given citing various examples. The methods are:

  1. Using While Loop
  2. Using Static Method
  3. Using Function
  4. Using Recursion

Using While Loop

1) Entered value will be assigned to n and res=0.

2) While loop iterates until n!=0, if n=0 then the loop terminated and prints the res  value.

  • example n=153, the condition is true ,a=3, res=(0*10)+3=3, n=15
  • n=15 condition true, a=5,res=30+5=35,n=1
  • n=1,condition true, a=1, res=35*10+1=351,n=0, so while loop terminated and prints reverse number.

Output:

Using Static Method

1) Here we have a static method reverse(int num), which calculates the reverse number.

2) The reverse method is called at the main method then reverse method executed and returns the reverse number, then prints the reverse number.

Output:

Reverse A Number In Java – Using Function

1) We are calculating the reverse of a number using for loop.

2) For loop iterates until n!=0, here the structure of for loop doesn’t contains the initialization ,increment / decrement.

3) For loop repeats these steps a=n%10; res=(res*10)+a; n=n/10; until the condition is false. if n=0 then it prints reverse of the number.

Output:

Using Recursion

1) In this program reverse(int num) is recursive, it calls itself until the condition is false.

2) Using Rev  class object r, call the method reverse(x ) as  r.reverse(x), then reverse(x) method starts the execution and calls itself as reverse(num)  until num!=0.

Output:

If you have any doubts or suggestions about Reverse A Number In Java program do leave a comment here.

More Programs:

x

Check Also

Prime Number Java Program – 1 to 100 & 1 to N | Programs

Prime Number Java Program –  Java Program to Check Whether a Number is Prime or ...