Reverse Integer
Reverse Integer is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the String Reversal subpattern.
Problem statement
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.
Topics and companies
Topics: Math, Simulation, Bit Manipulation.
How to practise Reverse Integer on Thita.ai
Starter code is provided in C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(log |x|), where the logarithm is the number of decimal digits in x. time and O(1) space.
Open Reverse Integer in the code editor, or read the Reverse Integer editorial for a worked solution with its approach and complexity analysis.
Where Reverse Integer sits in the DSA pattern sheet
- Two Pointers pattern guide
- String Reversal subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Reverse Integer
Other problems that use the same String Reversal and Two Pointers techniques:
- Reverse String — Easy, same subpattern
- Reverse String II — Easy, same subpattern
- Reverse Vowels of a String — Easy, same subpattern
- Reverse Words in a String — Medium, same subpattern
- Backspace String Compare — Easy, same pattern
- Boats to Save People — Medium, same pattern