Reverse Integer Leetcode Solution

In this post, we are going to solve the Reverse Integer Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Reverse Integer Leetcode Solution
Reverse Integer Leetcode Solution

Problem

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

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints:

  • -231 <= x <= 231 - 1

Now, lets see the leetcode solution of Reverse Integer Leetcode Solution.

Reverse Integer Leetcode Solution in Python

class Solution:
    def reverse(self, x):
        result = 0

        if x < 0:
            symbol = -1
            x = -x
        else:
            symbol = 1

        while x:
            result = result * 10 + x % 10
            x /= 10

        return 0 if result > pow(2, 31) else result * symbol

Reverse Integer Leetcode Solution in CPP

class Solution {
public:
    int reverse(int x) {
        int num = x;
        long int rev = 0;
        while(num != 0){
            int digit = num%10;
            rev = 10*rev + digit;
            if(rev > INT_MAX)return 0;
            if(rev < INT_MIN)return 0;
            num/=10;
        }
        return (int)rev;
    }
};

Reverse Integer Leetcode Solution in Java

class Solution {
    public int reverse(int x) {
        int num = x;
        long rev = 0;
        while(num != 0){
            int digit = num%10;
            rev = 10*rev + digit;
            if(rev > Integer.MAX_VALUE)return 0;
            if(rev < Integer.MIN_VALUE)return 0;
            num/=10;
        }
        return (int)rev;
    }
}

Note: This problem Reverse Integer is generated by Leetcode but the solution is provided by Chase2learn This tutorial is only for Educational and Learning purposes.

NEXT: String to Integer (atoi) Leetcode Solution

Sharing Is Caring

Leave a Comment