Example 1
- Input
- x = 123
- Output
- 321
The digits 123 mirrored give 321, which fits in the 32-bit range.
Reverse the decimal digits of a signed 32-bit integer x while keeping its sign. If the mirrored digits fall outside the signed 32-bit range, return 0.
Given a signed 32-bit integer x, return x with its digits reversed. A negative sign stays in front, so -123 becomes -321, and trailing zeros vanish because 120 becomes 21.
If the reversed digits fall outside the signed 32-bit range from to , return 0. The environment does not allow storing 64-bit integers, so the overflow must be detected before it happens.
0.The digits 123 mirrored give 321, which fits in the 32-bit range.
The sign stays in front while the digits 123 mirror to 321.
Mirroring gives 021, and the leading zero drops to leave 21.
Zero has no nonzero digit to move, so its reversed numeric value remains zero.
Its decimal reversal would be 9646324351, larger than 2147483647. Return zero rather than constructing that value in the solution.
The reversed negative digits still fit above the lower bound -2147483648, so retain the sign and return -2147483641.
Think of the input as a stack of decimal digits: taking the last digit of 123 yields 3, then 2, then 1, and appending them gives 321. A negative input must keep its sign while its digits change places. The difficult part is detecting overflow before an accumulator grows; comparing a textual candidate to the bound or guarding each arithmetic append avoids ever storing an out-of-range result.
Reveal String Reverse: intuition, complexity, and code
x % 10 and drop them with truncating division by 10.res = res * 10 + digit, mirroring the digit order.res against 214748364 so the overflow is caught while every value still fits.res * 10 + digit, when the damage is already done.x % 10 on negatives in Python, where the remainder stays non-negative and breaks the digit stream.21.Peel-and-push with % 10 and truncating division rebuilds any integer digit by digit, and bounds must be tested before the accumulator grows.