Reverse Integer
[[Bitwise operations]]
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
Brainstorming
Brute force
a number is denoted by the base of 10
so 123 is 1 * 100 + 2 * 10 + 3 * 1 we can reverse the integer and multiply it by the base with the power of 10 so it can become 3 * 100 + 2 * 10 + 1 * 1
100 = 10^2 10 = 10^1 1 = 10^0
integer = 120
str_int = str(integer)
negative = False
if "-" in str_int:
str_int = str_int[1:]
negative = True
n = len(str_int) - 1
powers = len(str_int) -1
reversed_int = []
for i in range(n, -1,-1):
result = int(str_int[i]) * pow(10, powers)
reversed_int.append(result)
powers -=1
if negative:
print(-1 * sum(reversed_int))
else:
print(sum(reversed_int))
- 🍅 (pomodoro::WORK) (duration:: 20m) (begin:: 2025-12-05 22:34) - (end:: 2025-12-05 22:56)
Optimised Solution
num = -123
negative = False
if num < 0:
negative = True
num *= -1
POSITIVE_LIMIT = pow(2,31) -1
NEGATIVE_LIMIT = pow(2,31)
rev = 0
while num:
digit = num % 10
if negative:
# We are building a number that will be negative.
# We must check if it will exceed NEGATIVE_LIMIT.
if rev > NEGATIVE_LIMIT // 10 or \
(rev == NEGATIVE_LIMIT // 10 and digit > NEGATIVE_LIMIT % 10):
print(0)
break
else: # It's a positive number
# We must check if it will exceed POSITIVE_LIMIT.
if rev > POSITIVE_LIMIT // 10 or \
(rev == POSITIVE_LIMIT // 10 and digit > POSITIVE_LIMIT % 10):
print(0)
break
rev = (rev * 10) + digit
num = num //10
if negative:
rev *=-1
print(rev)
- 🍅 (pomodoro::WORK) (duration:: 17m) (begin:: 2025-12-05 23:22) - (end:: 2025-12-05 23:45)
- 🥤 (pomodoro::BREAK) (duration:: 15m) (begin:: 2025-12-05 23:45) - (end:: 2025-12-06 00:00)