LeetCode:整数反转(Python版本)
2019-03-17 20:11
555 查看
LeetCode刷题日记
整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
Python代码
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x == 0: return 0 dect = 0 # 监测第一位是否为0 flag = 0 # 数值的正负监测 if x < 0: flag = 1 int2str = str(abs(x)) spilitint = [i for i in int2str] # 拆分数字为单个字符 for i in range(len(spilitint)): # 颠倒字符串 spilitint.insert(i, spilitint[-1]) spilitint.pop() while spilitint[dect] == '0': # 去掉位于首部的0 del spilitint[dect] if flag == 1: spilitint.insert(0, '-') str2 = ''.join(spilitint) str2int = int(str2) if str2int >= 2 ** 31 - 1 or str2int <= -2 ** 31: # 题目要求 return 0 return int(str2int)
相关文章推荐
- LeetCode--Reverse Integer(整数反转)Python
- LeetCode-Python-7. 整数反转
- LeetCode7.python实现:整数反转问题☆
- python实现leetcode-第七题-整数反转
- LeetCode:字符串转换整数 (atoi)(Python版本)
- leetcode的python实现 刷题笔记7: 反转整数
- LeetCode题解(python)-7. 整数反转
- Leetcode7.整数反转(python3)
- LeetCode-7-反转整数-c# 版本
- Leetcode 刷题(python)之 颠倒整数
- leetcode-整数反转
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- Leetcode:Reverse Integer ,整数反转
- [leetcode, python] Reverse Words in a String 反转字符串
- 用python写leetcode【5】 --字符串中的第一个唯一字符(387)、反转字符串(344)
- leetcode-反转链表II(python)
- LeetCode第七题--反转32位的整数
- LeetCode 7. 整数反转
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode题解(python)-13. 罗马数字转整数