CodingNodes / Bit Manipulation / Reverse Integer System design Space play · ←→ step · R restart

Problem

Given a signed 32-bit integer x, return the number you get by writing its digits in the opposite order. The sign stays where it is, and zeros that end up in front are dropped.

If the reversed value falls outside the signed 32-bit range [−2³¹, 2³¹ − 1], return 0. Assume the environment cannot hold 64-bit integers, so the overflow must be caught before it happens.

Constraints

  • −2³¹ ≤ x ≤ 2³¹ − 1

Examples: pick one to animate

Solutions

TimeO(log |x|) SpaceO(1)

Time: One loop per decimal digit, at most 10 for a 32-bit number.

Space: Only rev, digit and x are stored.

Take the last digit with x % 10 and drop it with x / 10 (both truncate toward zero, so negative numbers work with negative digits). Push the digit onto rev with rev * 10 + digit, but first check that this cannot pass the 32-bit limits: rev must not already be beyond 214748364 (or -214748364), and if it equals that value the new digit must be at most 7 (or at least -8), the last digits of 2147483647 and -2147483648. If the check fails, return 0.