LeetCode: Reverse Integer
Question: 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.
Solution:
class Solution: def reverse(self, x: int) -> int: convert_str = str(x) if "-" in convert_str: convert_str = convert_str[1:] converted_int = "-"+convert_str[::-1] else: converted_int = convert_str[::-1] converted_int = int(converted_int) if converted_int >= (2 ** 31 -1) or converted_int <= (-2 ** 31 -1): return 0 else: return converted_int
Comments
Post a Comment