Reverse integer LeetCode Solution

Reverse Integer LeetCode Solution :

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 – 1], then return 0.

• Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Reverse Integer LeetCode Solution :

Constraints :

•  -231 <= x <= 231 – 1

Approach for Reverse Integer LeetCode Solution : :

1. Initialize a variable ‘reverse’ to 0. This variable will hold the reversed integer.
2. Initialize another variable ‘num’ to the given integer. We will use ‘num’ to avoid modifying the original input integer.
3. While the ‘num’ is not equal to 0, extract the rightmost digit of ‘num’ using the modulo operator (%). Store this digit in a variable called ‘digit’.
4. Multiply ‘reverse’ by 10 and add the extracted digit ‘digit’ to it.
5. Divide ‘num’ by 10 and update ‘num’ with the quotient. This will remove the rightmost digit of ‘num’ in each iteration.
6. Repeat steps 3-5 until ‘num’ becomes 0.
7. Check if the reversed integer ‘reverse’ is within the range of a 32-bit signed integer. If it is not, return 0.
8. Return the reversed integer ‘reverse’.

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others