Reverse Integer LeetCode Solution

Here, We see Reverse Integer LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Reverse Integer LeetCode Solution

Reverse Integer LeetCode Solution

Problem Statement

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

Reverse Integer LeetCode Solution C++

class Solution {
public:
    int reverse(int x) {
        long r=0;
        while(x){
         r=r*10+x%10;
         x=x/10;
        }
        if(r>INT_MAX || r<INT_MIN) return 0;
        return int(r);      
    }
};Code language: PHP (php)

Reverse Integer LeetCode Solution Java

class Solution {
    public int reverse(int x) {
        long finalNum = 0;
        while(x!=0){
            int lastDig = x%10;
            finalNum += lastDig;
            finalNum = finalNum*10;
            x= x/10;
        }
        finalNum = finalNum/10;
        if(finalNum > Integer.MAX_VALUE || finalNum<Integer.MIN_VALUE){
            return 0;
        }
        if(x<0){
            return (int)(-1*finalNum);
        }
        return (int)finalNum;        
    }
}Code language: PHP (php)

Reverse Integer Solution JavaScript

var reverse = function(x) {
  const absReversed = Math.abs(x).toString().split('').reverse().join('');
  if (absReversed > 2**31) return 0;
  return absReversed * Math.sign(x);    
};Code language: JavaScript (javascript)

Reverse Integer Solution 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 resultCode language: HTML, XML (xml)
Scroll to Top