reversing a number code example

Example 1: reverse number in java

public class ReverseNumber {
    public static void main(String[] args) {
        int num = 1234, reversed = 0;

        while(num != 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num = num / 10;
        }
        System.out.println("Reversed Number: " + reversed);
}}

Example 2: reverse a number using arithmetic operations

//continue to loop until  a value is equal to 0

public class ReverseNum{
  
  public static void main(String[] args {
  
  int a = 543;
  int reverse = 0;
  
 while(a!=0){ //itera the process
 
 int digit = a%10; //isolate the last digit number
 
 reverse = digit + (reverse*10); //append last digit to reverse
 a=a/10; // remove the last digit from number
   } 
   System.out.println(reverse);
   
     } }

Example 3: print reverse number

void printReverse(int n) {
  if (n < 1) return;
  cout << n << endl;
  printReverse(n - 1);
}

printReverse(10);  /// 10 9 8 7 6 5 4 3 2 1

Tags:

Java Example