You get a 32-bit signed integer x. Return the number you get by writing its digits in the opposite order, keeping its sign. Zeros that end up at the front simply disappear, so 120 becomes 21.
If the reversed number does not fit in a 32-bit signed integer, from −2,147,483,648 to 2,147,483,647, return 0 instead. Pretend your machine has no 64-bit integers to help.
Example 1
Input: x = 456 Output: 654 Why: the digits 4, 5, 6 read backwards
2 more examples and the constraints
Example 2
Input: x = -890 Output: -98 Why: 098 loses its leading zero; the sign stays
Example 3
Input: x = 1999999999 Output: 0 Why: 9,999,999,991 is too big for 32 bits
Constraints
- −2,147,483,648 ≤ x ≤ 2,147,483,647
- Only 32-bit integers may be stored
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Reverse the textO(log |x|)
- Pop and push digits, check firstO(log |x|)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 10-digit x | Verdict |
|---|---|---|---|
| Reverse the text | O(log |x|) | Quick, but needs 64 bits | |
| Pop and push digits, check first | O(log |x|) | Best; stays inside 32 bits |
|x| = the size of x; it has about log₁₀|x| digits, at most 10.
Edge cases to test
- Trailing zeros. 120 gives 21 and 900000 gives 9.
- Zero. 0 gives 0; the loop never runs.
- Overflow on the last digit. 1563847412 would become 2,147,483,651, just past the top, so return 0.
- Just inside the limit. 1463847412 becomes 2,147,483,641, which fits.
- The smallest int. −2,147,483,648 reversed is far too big; and
absof it overflows in Java and C++.
Common mistakes
- Checking for overflow after
rev × 10 + digit, when the overflow has already happened. - Using Python's
%and//on negative numbers, which round down and give the wrong digits. - Taking
abs(x)of −2,147,483,648 in a 32-bit type, which overflows.
How to talk through it
- 1Clarify. What happens to trailing zeros? What should overflow return? Are 64-bit integers really off limits?
- 2Give the easy version. Reverse the digits as text and range-check. Point out that the check needs a 64-bit value.
- 3Pop and push. x % 10 gives the last digit, x / 10 drops it, rev × 10 + digit appends it.
- 4Guard before the push. Compare rev with INT_MAX / 10 and INT_MIN / 10, and the digit with 7 or −8, before multiplying.
- 5Test out loud. Run 120, a negative number, 0 and 1563847412 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?