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).
Example 1:
Input: x = 123
Output: 321
Reverse Integer LeetCode Solution :
Constraints :
- -231 <= x <= 231 – 1
Time Complexity:
Time Complexity: Tohe time complexity of the solution is O(log(x)). We need t extract the digits of the integer one by one until there are no more digits left. This process continues until the integer becomes 0. The number of iterations required depends on the number of digits in the integer, which is proportional to log(x) with base 10.
Space Complexity:
Space Complexity: The space complexity of the solution is O(1). We are only using a constant amount of extra space to store the reversed integer and a few other variables.
Approach for Reverse Integer LeetCode Solution : :
- Initialize a variable ‘reverse’ to 0. This variable will hold the reversed integer.
- Initialize another variable ‘num’ to the given integer. We will use ‘num’ to avoid modifying the original input integer.
- 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’.
- Multiply ‘reverse’ by 10 and add the extracted digit ‘digit’ to it.
- Divide ‘num’ by 10 and update ‘num’ with the quotient. This will remove the rightmost digit of ‘num’ in each iteration.
- Repeat steps 3-5 until ‘num’ becomes 0.
- Check if the reversed integer ‘reverse’ is within the range of a 32-bit signed integer. If it is not, return 0.
- Return the reversed integer ‘reverse’.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code for Validate Binary Search Tree LeetCode Solution : :
C++
Java
Python
C++
class Solution { public: int reverse(int x) { long reverse = 0; while(x!=0){ int digit = x%10; reverse = reverse*10 + digit; x=x/10; } if(reverse>INT_MAX || reverse
Java
class Solution { public int reverse(int x) { long reverse = 0; while (x != 0) { int digit = x % 10; reverse = reverse * 10 + digit; x = x / 10; } if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0; return (int) reverse; } }
Python
class Solution(object): def reverse(self, x): reverse = 0 sign = -1 if x < 0 else 1 x = abs(x) while x: digit = x % 10 reverse = reverse * 10 + digit x /= 10 result = sign * reverse if result > 2 ** 31 - 1 or result < -(2 ** 31): return 0 return result
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
Login/Signup to comment