tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Articles > Java > Coding Examples > Reverse a Number

Reverse a Number 

Print reverse number of a given number.

File Name  :  
com/bethecoder/tutorials/coding/examples/ReverseNumberTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.coding.examples;

public class ReverseNumberTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    long [] nums = 12345678786121, -2, -34, -386 };
    for (long num : nums) {
      System.out.println("Reverse of number '" + num + "' : " + reverseNumber(num));
    }
  }

  private static long reverseNumber(long number) {
    long revNum = 0;
    
    while (number % 10 != 0) {
      revNum = (revNum * 10(number % 10)
      number = number/10;
    }
    
    return revNum;
  }
  
}
   

It gives the following output,
Reverse of number '12345678' : 87654321
Reverse of number '786' : 687
Reverse of number '12' : 21
Reverse of number '1' : 1
Reverse of number '-2' : -2
Reverse of number '-34' : -43
Reverse of number '-386' : -683


                    Print

   



Books Recommendation

 
 
bl  br