Today we are going to be visiting a very simple problem, which need some basic maths though. Given an integer, reverse it and return the reversed integer. Sample runs are: 135 -> 531, -12 -> -21, 0 -> 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* * @Author: Ajk Palikuqi * * @Question: How To Reverse Integer * i.e. 135 will return 531. -12 will return -21. */ package iqLib.bitLib; public class ReverseInteger { public static void main (String[] args) { System.out.println(getReversed(135)); System.out.println(getReversed(-12)); System.out.println(getReversed(0)); } public static int getReversed(int number) { int reversed = 0; while (number != 0) { reversed *= 10; reversed += (number % 10); number /= 10; } return reversed; } } |
Like we said before, looks fairly simple. Two notes:
1. We are using Java’s integer “special” division, in which -1/2 = 0 (whereas in other languages such as C, it would return -1, which is actually what rounding down is supposed to give)
2. We are not using auxiliary space! Don’t get fooled by Java’s extensive API and think of solving this by making a String/StringBuilder followed by calling the reverse method. Note that in that case you would use O(n) auxiliary space where n is the number of digits in our integer.
The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂
Latest posts by Ajk (see all)
- Find Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017