Reverse Integer Algorithm in C++, Java, and Python - LeetCode Problem

Featured image

Reverse Integer is the medium-level problem of LeetCode. In this post, we will see the solution to this problem in C++, Java, and Python.

Problem Statement and Explanation

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 -2**31, 2**31 - 1, then return 0.

Example 1:

input: 134
output: 431

Example 2:

input: -312
output: -213

Reverse Integer Python Solution in Python

Reverse Integer Java Solution in Java

Reverse Integer C++ Solution in C++

Explanation of Solution

Time Complexity of the Solution

The time complexity of the solution is O(n), where n is the number of digits in the original number. This is because the while loop iterates n times.

Here is a breakdown of the time complexity of each step in the function:

Space Complexity of the Solution

The space complexity of the solution is O(1), since the function only uses a constant number of variables. Here is a breakdown of the space complexity of each step in the function: