LeetCode 7: Reverse Integer – Python & JavaScript Solutions with Explanation

LeetCode 7: Reverse Integer - Python & JavaScript Solutions

Reverse Integer - LeetCode Problem 7

Difficulty: Medium

Problem Statement

Given a signed 32-bit integer x, return x with its digits reversed.

Example

    Input: x = 123
    Output: 321
    

Approach & Explanation

To reverse an integer, we can:

  • Convert it to a string, reverse it, and convert it back.
  • Handle negative numbers by keeping track of the sign.
  • Check for **integer overflow** (if the result exceeds 32-bit limits).

Python Solution:


def reverse(x: int) -> int:
    sign = -1 if x < 0 else 1
    rev = int(str(abs(x))[::-1])
    return sign * rev if -2**31 <= rev * sign <= 2**31 - 1 else 0
    

JavaScript Solution:


function reverse(x) {
    let sign = x < 0 ? -1 : 1;
    let rev = parseInt(String(Math.abs(x)).split("").reverse().join("")) * sign;
    return rev >= -(2**31) && rev <= 2**31 - 1 ? rev : 0;
}
    

Edge Cases

  • Large numbers: Reverse must stay within 32-bit range.
  • Negative numbers: Should maintain the sign.
  • Trailing zeros: 120 → 21.

Time Complexity

O(log n) because we process each digit.

Comments

Popular posts from this blog

LeetCode Problem #10: Regular Expression Matching - Explanation and Solutions in Python and JavaScript

LeetCode Problem #1: Two Sum - Explanation and Solutions in Python and JavaScript

LeetCode Problem #2: Add Two Numbers - Explanation and Solutions in Python and JavaScript