Show problems as
Classic problem #7MediumMath

Reverse Integer

Real-world version: Legacy Register Flip
Tracked in this browser only
Read Reverse Integer on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstString Manipulation · Strings, animated step by step

An old flow meter transmits its counter as reading, a signed whole number. The meter's firmware was wired back to front, so the decimal digits arrive in the opposite order to the one intended, and the decoder has to undo that: keep the sign as it is and read the digits the other way round. Any zeros that end up in front simply vanish, since the decoded counter is a number rather than a run of characters, so a reading of 4100 decodes to 14.

The decoder is a small board with one signed 32-bit register, so it can only ever hold a value from -2^31 through 2^31 - 1. Nothing wider is available: no 64-bit slot, no unbounded arithmetic, and no scratch buffer of characters. If the decoded counter would fall outside what the register holds, the decoder gives up and reports 0. Return the decoded counter.

Examples

Example 1

Input
reading = 8104
Output
4018

Reading the digits 8, 1, 0, 4 the other way round gives 4, 0, 1, 8.

Example 2

Input
reading = -3570
Output
-753

The digits flip to 0, 7, 5, 3 and the leading zero drops away, while the sign rides along unchanged.

Example 3

Input
reading = 1999999999
Output
0

The flipped digits spell a counter above 2^31 - 1, which the register cannot hold, so the decoder reports failure.

Constraints

  • -2^31 <= reading <= 2^31 - 1
  • No value outside the signed 32-bit range may be held at any point, so overflow has to be ruled out before it happens

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def flip_register(reading: int) -> int:
Java
public int flipRegister(int reading)