Reverse Integer

35 min · reverse()

Turning a number around looks like a string trick until the reversed digits no longer fit inside the integer type.

Given a signed 32-bit integer x, reverse its decimal digits and return the result. A signed 32-bit integer is an integer in the range -2^31 through 2^31 - 1. Preserve the sign, and let zeros at the old right edge disappear after reversal.

If the reversed value falls outside that range, return 0. This out-of-range event is called integer overflow.

A few ground rules:

  • The minus sign isn't a digit; it stays at the front of a negative answer.
  • Leading zeros aren't kept in an integer result.
  • Check the range before accepting the next digit into the answer.

Constraints

  • -2^31 <= x <= 2^31 - 1

Hints

A direct representation

The magnitude is the value without its sign. Reverse the magnitude's decimal characters, convert back to a number, then apply the sign and range check.

Pop one digit

Remainder by 10 gives the last digit. Integer division by 10 removes it. Append that digit to the result with result * 10 + digit.

Check before multiplying

Before result * 10 + digit, compare result with the last safe prefix. Positive results may end in at most 7; negative results may end in at most 8 in magnitude.

Follow-up

Can you reverse the number with arithmetic alone and constant extra space?

Visible cases

Examples

Example 1

ready
Input
x = 123
Expected
321
Why
the three digits trade places

Example 2

ready
Input
x = -123
Expected
-321
Why
the sign stays negative while the digits reverse

Example 3

ready
Input
x = 120
Expected
21
Why
the old trailing zero becomes a dropped leading zero

Interview signal

Asked at

AmazonBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite