Leetcode #7 — Reverse Integer (Python)
2 min readDec 20, 2020
Hello everyone, today we’ll be looking at the Reverse Integer problem. This one is marked as “Easy” on Leetcode.
Problem Statement
Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Examples from Leetcode
Example 1:
Input: x = 123
Output: 321
Output Explained:
This one is pretty simple, we just need to reverse all of the digits of the given integer, so 123 will become 321.
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Solution
Submission on Leetcode:
Explanation (with two examples):
1. Let's call: reverse(4567) - Since 4567 > 0, convert 4567 into a string, reverse that string using [::-1], and then convert the string back to an int. So result = 7654- The number 7654 is returned because -2^31 <= 7654 <= 2^31 - 12. Let's call: reverse(-321)- Since -321 < 0, take the absolute value of -321 using abs(-321), which is 321. Convert the int 321 into a string using str(-321), reverse it using [::-1] and add '-' in front of it as -321 < 0. So the string '-123' will get converted to an int once again using int('-123'). As a result, result = -123- The number -123 is returned as -2^31 <= -123 <= 2^31 - 1
That’s all, folks! Happy learning!
Dhairya Dave