Skip to main content

Reverse Integer

Medium
Data Structures and Algorithms
Editorial
Topics:
Math
Simulation
Bit Manipulation

Implement Solution.reverse, which receives the integer x and reverses the order of its decimal digits. The sign, if any, remains in front of the reversed digits; leading zeroes in the reversed decimal representation are discarded automatically.

A 32-bit signed integer is an integer from -2^31 through 2^31 - 1, inclusive. Return the reversed integer when it lies in that range. If the reversed value lies outside that range, return 0. The calculation must account for the fact that 64-bit integers are unavailable.

Example 1:

Input: x = 12030
Output: 3021
Explanation: Reversing the decimal digits gives 03021, whose integer value is 3021 because leading zeroes are discarded.

Example 2:

Input: x = -804
Output: -408
Explanation: The digits 804 reverse to 408, and the original negative sign remains negative.

Example 3:

Input: x = 2147483641
Output: 1463847412
Explanation: The reversed value is within the 32-bit signed range, so it is returned unchanged as a valid result.

Constraints:

  • x is a JSON integer.
  • -2^31 <= x <= 2^31 - 1.
  • The input contains exactly one parameter named x.
  • The result must be returned as a JSON integer.

Need help or want more practice?

Practise in an interviewGet AI Coach help