[LeetCode] Reverse Integer
Với 10 dòng code cùng xem Python giải quyết một bài toán tầm medium trên LeetCode như thế nào?
Hôm nay cùng tôi giải quyết một bài toán trên LeetCode với Python nha. Hãy xem với 10 dùng code chúng ta có thể giải quyết được bài toán này không?
Đầu bài: Reverse Integer:
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.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Và đây là cách tôi giải quyết bài toán
Đây là mã code đầy đủ của tôi
class Solution:
def reverse(self, x: int) -> int:
# Lưu trữ dấu của số
sign = -1 if x < 0 else 1
# Đảo ngược các chữ số và chuyển đổi lại thành số nguyên
reversed_num = int(str(abs(x))[::-1]) * sign
# Kiểm tra tràn
if reversed_num < -2**31 or reversed_num > 2**31 - 1:
return 0
return reversed_num
Kết quả tôi nhận được khá tốt:
Nếu bạn có thuật toán tốt hơn hãy chia sẻ với tôi.
Cảm ơn bạn đã quan tâm đến bài viết của tôi.
All rights reserved