Quick revision
The short answer
Reversing the digits of an integer is a math problem about digits. We repeatedly take the last digit with x % 10, drop it with x / 10, and append it to the result with rev * 10 + digit, checking before each append that the result will still fit in an int and returning 0 if it will not. The loop runs once per digit, at most ten times for an int, and uses O(1) space.
The solution
What it costs
| Approach | Time | Extra space | Needs 64-bit? |
|---|---|---|---|
| Reverse the text, parse as long | O(d) | O(d) | yes |
| Arithmetic, result kept in a long | O(d) | O(1) | yes |
| Arithmetic, check before multiplying | O(d) | O(1) | no |
What to remember
We reversed the digits of an integer the way we would move books between two shelves, one from the right end at a time: x % 10 takes the last digit, x / 10 drops it, and rev * 10 + digit stands it at the right end of the result. The overflow test against Integer.MAX_VALUE / 10 and Integer.MIN_VALUE / 10 runs before every multiplication, so a wrong value never appears. It takes at most ten rounds and O(1) space. The clue to remember is the phrase the digits of an integer: use % 10, / 10 and * 10, and check for overflow before it happens.
1Moving digits from one shelf to another
Imagine a short shelf of books, each with one digit on its spine, standing in the order 1, 2, 3, 4. You want a second shelf with the same books in the opposite order. A simple way is to keep taking the book at the right end of the old shelf and standing it at the right end of the new shelf. The first book you move is 4, so it ends up first on the new shelf. Then 3 goes to its right, then 2, then 1, and the new shelf reads 4, 3, 2, 1. Every book moved once, and the order came out reversed by itself.
That is exactly how we will reverse a number. We are given a 32-bit int, x, and must return the int whose decimal digits are in the opposite order, keeping the sign. So 1234 becomes 4321, and -120 becomes -21. Why -21 and not -021? Because the reversed digits are 0, 2, 1, and a zero at the front of a number means nothing, so 021 is just 21.
Let us work one by hand with the shelf. For 1234, the rightmost book is 4, so the new number starts as 4. Then 3 joins on the right, giving 43, then 2 gives 432, and 1 gives 4321.
The cells are the digits of x as we write them. The reverse reads the same cells from right to left.
- x
- 1234
- answer
- 4321
- another x
- -120
- its answer
- -21
1x = 1234 has the digits 1, 2, 3, 4. Read from the right they give 4321, which is the answer; for -120 the answer is -21.
What to assume
- What should we return when the reverse does not fit?
- The common version says 0.
- Does the sign stay in front?
- Yes.
- And may we use a 64-bit long to hold the result while we build it?
- The strict version says no, as if the machine could only store 32-bit integers, and we follow that rule.
There is one more thing about the new shelf: it has a fixed length. A Java int can only hold values from -2,147,483,648 to 2,147,483,647, about two billion either way. Many numbers that fit reverse into numbers that do not. 1534236469 fits, but its reverse, 9646324351, is almost ten billion. That is the one real difficulty in this problem, and the rest is smaller than it looks.
So a careful candidate's questions are mostly about the edges. What should we return when the reverse does not fit? The common version says 0. Does the sign stay in front? Yes. And may we use a 64-bit long to hold the result while we build it? The strict version says no, as if the machine could only store 32-bit integers, and we will meet that rule rather than avoid it. We also show the long version in a follow-up, because some interviewers allow it.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a digit arithmetic problem
Most beginners read this question and think of text. A number printed on the screen is a row of characters, and reversing a row of characters is easy, so why not turn the number into a String, reverse it and turn it back? That is a fair first idea, and it is our first attempt below. But the question is about an int, and the clue is to stay with numbers.
The first clue is the phrase the digits of an integer. Whenever a question works on decimal digits, such as summing them, counting them, checking whether a number reads the same both ways, or reversing it, there are three small pieces of arithmetic that do all the work. x % 10 gives the last digit, because % is the remainder after dividing, and the remainder after dividing by 10 is whatever is in the ones place: 1234 % 10 is 4. x / 10 removes the last digit, because integer division throws away the remainder: 1234 / 10 is 123. And r * 10 + d puts the digit d at the right end of r: 43 * 10 + 2 is 432.
The second clue is the type, a 32-bit integer. Any time we build a number by multiplying, we must think about overflow, which is what happens when a result is too big for its type. Java does not warn us; it silently wraps around to a wrong value, the way an old car's mileage counter rolls back to all zeros after its largest reading.
Together these point to the math and bits family, and within it the digit arithmetic pattern: read a number from right to left with % 10 and / 10, and build another from left to right with * 10 and +. The general rule to carry to new problems is that decimal digits can be handled without any strings at all, and that every multiplication on a fixed size type needs an overflow check before it happens, not after.
Some patterns look similar but do not fit. Bit manipulation also works on the digits of a number, but on binary digits, using operators such as & and >>, not on decimal ones. Two pointers swapping characters at both ends of a char array would also reverse the digits, but only after turning the number into text, which is the brute force again.
3The honest first attempt, reversing the text
The honest first attempt lets the library do the work. We turn the absolute value of x into text, reverse the text, parse it back into a number, put the sign back, and check whether the result fits in an int. We parse into a long, Java's 64-bit integer, so that a reverse that is too big is still visible to us instead of throwing an exception.
Let us read it in the order it runs. Math.abs((long) x) first widens x to a long and then drops its sign; the widening matters for one value, as we will see. Long.toString turns 120 into the text "120", StringBuilder.reverse turns that into "021", and Long.parseLong reads "021" as 21, quietly losing the leading zero, which is just what we want. Then we put the minus sign back for a negative x, and if the long is outside the int range we return 0; otherwise we cast it to an int.
It works on every example, and the cost is small: an int has at most ten digits, so the time and the space are both proportional to the number of digits, d. So where is the waste? It builds several objects, a String, a StringBuilder and another String, for something the processor can do with two int variables. It needs special care for Integer.MIN_VALUE, -2147483648, whose absolute value 2147483648 does not fit in an int, which is why we widened to long first. And it depends entirely on a 64-bit type to notice the overflow. Under the strict rule that we may only store 32-bit values, this approach has no answer at all.
So let us ask the question that leads further: do we really need the text? The digits are already there inside the number, and % 10 and / 10 can take them out one at a time.
4Moving the digits with arithmetic, and checking before we multiply
We now do the shelf exercise with arithmetic. We start with rev = 0, the empty new shelf. In each round, digit = x % 10 takes the last digit of x, x /= 10 removes it, and rev = rev * 10 + digit stands it at the right end of rev. Multiplying by 10 shifts every digit already in rev one place to the left, which opens an empty ones place, and adding the digit fills it. We stop when x becomes 0, because then no digits are left.
A beginner usually asks next what happens with a negative number. Do we need to remove the sign, reverse, and put it back? In Java we do not, because % keeps the sign of the number being divided. For -120, -120 % 10 is 0 and x becomes -12; -12 % 10 is -2 and x becomes -1; -1 % 10 is -1 and x becomes 0. So rev grows 0, then 0 * 10 + (-2) = -2, then -2 * 10 + (-1) = -21. The sign travels with every digit. The trailing zero of -120 vanishes on its own too, because 0 * 10 + 0 is still 0.
Now the overflow, the only hard part. The tempting mistake is to compute rev * 10 + digit and then check whether the answer looks too big. That cannot work, because by then Java has already wrapped the value around, and the wrapped value is a perfectly ordinary looking int. We must check before we multiply.
So when is rev * 10 + digit too big? The largest int is 2147483647. If rev is already bigger than 214748364, which is Integer.MAX_VALUE / 10, then rev * 10 is at least 2147483650, already too big whatever the digit. If rev equals 214748364 exactly, then rev * 10 is 2147483640, and adding a digit bigger than 7 would pass 2147483647. The negative side mirrors it: the smallest int is -2147483648, so we return 0 if rev is below -214748364, or equal to it with a digit below -8. The picture shows the check catching an overflow.
The digits of x. Digits already moved into rev are marked done; the digit about to be moved is marked now.
- x
- 1534236469
- rev
- 0
- limit / 10
- 214748364
1x = 1534236469 fits in an int, but its reverse, 9646324351, would not. We pop digits from the right as usual.
- x
- 1
- rev
- 964632435
- digit
- 1
- limit / 10
- 214748364
2Nine digits are moved safely, 9, 6, 4, 6, 3, 2, 4, 3, 5, and each time rev was small enough. Now rev = 964632435 and only the digit 1 is left.
- rev
- 964632435
- test
- 964632435 > 214748364
- return
- 0
3Before multiplying, we test rev > 214748364. It is, since 964632435 is far bigger, so rev * 10 would overflow and we return 0 without computing it.
Notice what happened in the last frame. We never computed 964632435 * 10, so no wrong value ever existed in our program. The comparison only used numbers that fit, Integer.MAX_VALUE / 10 being one of them.
There is a small fact that surprises people here. For an int input, the case where rev equals 214748364 and the digit is larger than 7 can never actually happen, because a ten digit int starts with 1 or 2, so the last digit we add is at most 2. We keep the full test anyway. It costs nothing, and it makes the code obviously correct to anyone who reads it, which matters more in an interview than saving one comparison.
5Watching 1234 move across, digit by digit
The picture runs the loop on x = 1234. The cells are the digits of the original number; each one is marked done once it has moved into rev. The panel shows x, the digit just popped, the result of the overflow check and rev.
Watch rev grow from the left, 4, then 43, then 432, while x shrinks from the right, 123, then 12, then 1.
The cells are the digits of the original x. A digit marked done has moved from x to the end of rev.
- x
- 1234
- rev
- 0
1We start with x = 1234 and rev = 0, an empty new number. The loop runs while x is not 0.
- x
- 123
- digit
- 4
- rev
- 0
2digit = x % 10 = 4 takes the last digit, and x /= 10 drops it, so x becomes 123.
- x
- 123
- digit
- 4
- check
- safe
- rev
- 4
3rev = 0 is far below the limit, so the check passes, and rev = 0 * 10 + 4 = 4. The 4 is now the first digit of rev.
- x
- 12
- digit
- 3
- check
- safe
- rev
- 43
4The next round pops 3 and x becomes 12. The check passes, and rev = 4 * 10 + 3 = 43, so the 3 lands to the right of the 4.
- x
- 1
- digit
- 2
- check
- safe
- rev
- 432
5The next round pops 2 and x becomes 1. The check passes, and rev = 43 * 10 + 2 = 432.
- x
- 0
- digit
- 1
- check
- safe
- rev
- 4321
6The last round pops 1 and x becomes 0. The check passes, and rev = 432 * 10 + 1 = 4321.
- x
- 0
- return
- 4321
- rounds
- 4
7Now x is 0, so the loop test x != 0 fails, and we return rev = 4321 after four rounds, one per digit.
Let us read the first round slowly, because its order matters. In frame 2 we pop before we do anything else: digit is 4 and x becomes 123. In frame 3 we check rev, which is 0 and far below the limit, and only then do we compute rev = 0 * 10 + 4. If we multiplied first and checked afterwards, the check would be useless, as we saw.
Each later frame repeats the same three lines. In the last round x becomes 0, so the loop test fails and we return 4321, after four rounds for four digits. For -120 the same loop runs three rounds, with rev going 0, -2, -21, exactly as we worked out by hand.
6The complete Java program
Here is the whole program. main covers a plain case, a negative number with a trailing zero, zero itself, a large value whose reverse just fits, a value whose reverse overflows, and Integer.MIN_VALUE. Each comment shows what that line prints.
Let us read reverse in the order it runs. rev starts at 0. The loop runs while x != 0, so zero itself skips the loop and returns 0 at once.
Inside the loop, digit = x % 10 takes the last digit, negative when x is negative, and x /= 10 drops it from x. Then come the two checks, both made before the multiplication. The first compares rev with Integer.MAX_VALUE / 10, which is 214748364, and the second with Integer.MIN_VALUE / 10, which is -214748364. If either says the next step would leave the int range, we return 0 straight away. Only when both pass do we run rev = rev * 10 + digit.
The fourth line of main is worth a look. 1463847412 reverses to 2147483641. In its last round rev is exactly 214748364 and the digit is 1, not more than 7, so the check passes and the result is just inside the range. The fifth line, 1534236469, is the one from the picture and returns 0. Integer.MIN_VALUE reverses to -8463847412, far below the range, and also returns 0. So main prints 4321, -21, 0, 2147483641, 0 and 0.
7How much it costs, and the cases at the edges
Let us count on the example first. 1234 has four digits, and the loop ran four rounds, each a remainder, a division, two short checks and one multiply and add. For a number with d digits the loop runs d times, and d is about log10 of |x|, the number of times we can divide by 10 before reaching 0. So the time is O(log |x|), and for any int that is at most ten rounds. The space is O(1): rev, x and digit, three ints.
The text version was also proportional to the number of digits, so the gain is not in how the time grows. It is in what we avoid: no objects, no special handling of Integer.MIN_VALUE, and no need for a 64-bit type.
| Approach | Time | Extra space | Needs 64-bit? |
|---|---|---|---|
| Reverse the text, parse as long | O(d) | O(d) | yes |
| Arithmetic, result kept in a long | O(d) | O(1) | yes |
| Arithmetic, check before multiplying | O(d) | O(1) | no |
Now the edges, all of which main tests. Zero never enters the loop. Trailing zeros vanish, because they become leading zeros of rev. Negative numbers keep their sign through Java's remainder rule, with no special case. Any input whose reverse is too big or too small returns 0, including Integer.MIN_VALUE. And because the code never takes an absolute value, it never meets the one int whose absolute value cannot be stored.
8Follow-up questions
How would you solve it if you were allowed to use a long?
We keep the same loop but declare rev as a long. A long holds the reverse of any int, since the largest reverse is under ten billion, so no check is needed inside the loop. After the loop, if rev is below Integer.MIN_VALUE or above Integer.MAX_VALUE, we return 0; otherwise we cast it to int. It is shorter and easier to read, and it is a perfectly good answer whenever the interviewer permits it.
How do you check whether an integer is a palindrome with the same idea?
A palindrome number reads the same both ways, like 1221. Negative numbers are not palindromes, and neither is any number that ends in 0 except 0 itself. For the rest, we reverse only the second half: we pop digits from x into rev while x is bigger than rev. For 1221 that leaves x = 12 and rev = 12, which are equal. For an odd digit count, like 12321, we end with x = 12 and rev = 123, and we compare x with rev / 10, which drops the middle digit. Reversing only half also means rev can never overflow.
Why not use Math.abs on x and handle the sign at the end?
Because Math.abs(Integer.MIN_VALUE) is still Integer.MIN_VALUE. Its positive partner, 2147483648, is one more than the largest int, so it cannot be stored, and the result wraps back to the same negative number. Code that takes the absolute value and then pops digits would get negative digits where it expects positive ones. Working with the signed remainder, as our solution does, avoids that trap entirely.
9Conclusion
We reversed the digits of an integer the way we would move books between two shelves, one from the right end at a time: x % 10 takes the last digit, x / 10 drops it, and rev * 10 + digit stands it at the right end of the result. The overflow test against Integer.MAX_VALUE / 10 and Integer.MIN_VALUE / 10 runs before every multiplication, so a wrong value never appears. It takes at most ten rounds and O(1) space. The clue to remember is the phrase the digits of an integer: use % 10, / 10 and * 10, and check for overflow before it happens.
Open with
Let me confirm the rules: I keep the sign, leading zeros that come from trailing zeros disappear, and I return 0 if the reverse does not fit in a 32-bit int.
Then, if they want more
May I use a long? If not, I will check overflow without one. The quick solution is to turn the number into a string, reverse it and parse it back as a long, which works but builds objects and relies on a 64-bit type to notice overflow.
Since this is about decimal digits, I will use digit arithmetic. x mod 10 gives the last digit, x divided by 10 removes it, and rev times 10 plus the digit appends it. Java's remainder keeps the sign, so negative numbers need no special case, and trailing zeros vanish because zero times ten plus zero is zero.
The important part is overflow. Before multiplying, I check whether rev is greater than Integer.MAX_VALUE over 10, or equal to it with a digit above 7, and the mirror test against MIN_VALUE over 10 with a digit below minus 8. If either holds, I return 0. I check before multiplying because int arithmetic wraps silently.
The loop runs once per digit, at most ten times, with constant space. I would test zero, a negative number ending in zero, a large value that just fits, one that overflows, and Integer.MIN_VALUE.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 17 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Reverse the digits of an integer.": https://scrivio-interview-library.netlify.app/data-structures/solutions/reverse-the-digits-of-an-integer-9a7ac1/