1. # 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
    2. #
    3. # 示例 1:
    4. #
    5. # 输入: 123
    6. # 输出: 321
    7. #
    8. #
    9. # 示例 2:
    10. #
    11. # 输入: -123
    12. # 输出: -321
    13. #
    14. #
    15. # 示例 3:
    16. #
    17. # 输入: 120
    18. # 输出: 21
    19. #
    20. #
    21. # 注意:
    22. #
    23. # 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
    24. # Related Topics 数学
    25. # 👍 2104 👎 0
    26. # leetcode submit region begin(Prohibit modification and deletion)
    27. class Solution(object):
    28. def reverse(self, x):
    29. """
    30. :type x: int
    31. :rtype: int
    32. """
    33. res = ''
    34. if x > 0:
    35. res = str(x)[::-1]
    36. else:
    37. res = str(-x)[::-1]
    38. res = int(res)
    39. if -231 <= res <= 231 - 1:
    40. return res
    41. else:
    42. return 0
    43. # 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
    44. #
    45. # 示例 1:
    46. #
    47. # 输入: 123
    48. # 输出: 321
    49. #
    50. #
    51. # 示例 2:
    52. #
    53. # 输入: -123
    54. # 输出: -321
    55. #
    56. #
    57. # 示例 3:
    58. #
    59. # 输入: 120
    60. # 输出: 21
    61. #
    62. #
    63. # 注意:
    64. #
    65. # 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
    66. # Related Topics 数学
    67. # 👍 2104 👎 0
    68. # leetcode submit region begin(Prohibit modification and deletion)
    69. class Solution:
    70. def reverse(self, x: int) -> int:
    71. """
    72. :type x: int
    73. :rtype: int
    74. """
    75. res = 0
    76. if x > 0:
    77. res = str(x)[::-1]
    78. else:
    79. res = '-' + str(-x)[::-1]
    80. res = int(res)
    81. if -2 ** 31 <= res <= 2 ** 31 - 1:
    82. return res
    83. else:
    84. return 0
    85. # leetcode submit region end(Prohibit modification and deletion)
    86. s = Solution()
    87. print(s.reverse(123))
    88. print(s.reverse(-123))