Leetcode7.整数反转(python3)
2019-01-26 09:27
357 查看
Leetcode7.整数反转
题目描述:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
实例:
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
解法1:(python)
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x >= 0: y = int(str(x)[::-1]) if -2**31 <= y <= 2**31 - 1: return y else: return 0 if x < 0: y = -int(str(-x)[::-1]) if -2**31 <= y <= 2**31 - 1: return y else: return 0
解法2:(python)
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ reverse = False if x < 0: reverse = True x = -x new = 0 while x>0: tmp = x%10 x //= 10 new = new*10 + tmp if reverse: new = -new return new if new < 2147483648 and new >= -2147483648 else 0
补充:
1.[:-1]和[::-1]用法
a='python' b=a[::-1] print(b) #nohtyp c=a[::-2] print(c) #nhy #从后往前数的话,最后一个位置为-1 d=a[:-1] #从位置0到位置-1之前的数 print(d) #pytho e=a[:-2] #从位置0到位置-2之前的数 print(e) #pyth
相关文章推荐
- LeetCode7.python实现:整数反转问题☆
- python实现leetcode-第七题-整数反转
- LeetCode--Reverse Integer(整数反转)Python
- LeetCode题解(python)-7. 整数反转
- leetcode的python实现 刷题笔记7: 反转整数
- Java&LeetCode 初入门——007. 整数反转
- LeetCode第七题--反转32位的整数
- [leetcode, python] Reverse Words in a String 反转字符串
- 【LeetCode】- Reverse Integer(将一个整数反转)
- leetcode——Reverse Integer 反转整数数字(AC)
- LeetCode Reverse Integer 反转整数
- python入门习题——7,反转整数(简单)
- LeetCode题解(python)-12. 整数转罗马数字
- LeetCode 7. Reverse Integer 整数反转
- [leetcode, python] Reverse Words in a String 反转字符串
- leetcode-344. 反转字符串[python]
- leetcode之7整数反转
- LeetCode 7. Reverse Integer(整数反转)
- LeetCode 7 :Reverse Integer ---- 反转int整数
- LeetCode 345. 反转字符串中的元音字母 Python