How to Reverse a Number in Java

The challenge

Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321)

Numbers should preserve their sign; i.e. a negative number should still be negative when reversed.

Examples

123 -> 321 -456 -> -654 1000 -> 1

The solution in Java code

Option 1:

public class ReverseNumber { public static int reverse(int number) { int result = 0; while(number != 0) { result = result * 10 + number % 10; number = number / 10; } return result; } }
Code language: Java (java)

Option 2:

public class ReverseNumber { public static int reverse(int n) { return Integer.valueOf(new StringBuilder(""+n) .reverse() .toString() .replace("-","") ) * Integer.signum(n); } }
Code language: Java (java)

Option 3:

public class ReverseNumber { public static int reverse(int number) { String temp = ""; if(number < 0){ temp += "-"; number = Math.abs(number); } String num = "" + number; for(int i = num.length()-1; i >= 0; i--){ temp += num.charAt(i); } return Integer.parseInt(temp); } }
Code language: Java (java)

Test cases to validate our solution

import static org.junit.Assert.assertEquals; import org.junit.Test; public class ReverseNumberTest { @Test public void reverse() throws Exception { assertEquals( 321, ReverseNumber.reverse( 123 ) ); assertEquals( -321, ReverseNumber.reverse( -123 ) ); assertEquals( 1, ReverseNumber.reverse( 1000 ) ); assertEquals( 4321234, ReverseNumber.reverse( 4321234 ) ); assertEquals( 5, ReverseNumber.reverse( 5 ) ); assertEquals( 89898989, ReverseNumber.reverse( 98989898 ) ); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments