LeetCode每日一题——T7. 整数反转(易):反转字符串
2019-06-26 21:36
507 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41514090/article/details/93783325
法一:用原数除10取余的方法;
注意:python属于向下取余,即 5 / 2 = 2,而 (-5) / 2 = -3。因此,需要先将原数取绝对值再计算。
class Solution: def reverse(self, x: int) -> int: x_abs = abs(x) num = 0 err = (2 ** 31) - 1 if x > 0 else 2 ** 31 # 等于 err = (1 << 31) - 1 if x > 0 else 1 << 31 while x_abs != 0: num = num *10 + x_abs % 10 if num > err: return 0 x_abs //= 10 # 要用地板除法 return num if x > 0 else -num
法二:反转字符串法:
将原数符号位取出,剩余部分转为字符串,反转字符串,然后再转为整数,乘以符号位输出。
1)直接对字符串元素进行反转:
class Solution: def reverse(self, x: int) -> int: x_abs = abs(x) sign = 1 if x >= 0 else -1 x_str = str(x_abs) x_str_reverse = x_str[::-1] x_out = int(x_str_reverse) * sign if -2 **31 <= x_out <= 2 ** 31 - 1: return x_out else: return 0
2)借助列表进行反转(速度反而比直接反转快):
class Solution: def reverse(self, x: int) -> int: x_abs = abs(x) sign = 1 if x >= 0 else -1 x_str = str(x_abs) x_list = list(x_str) x_list.reverse() x_str_reverse = "".join(x_list) x_out = int(x_str_reverse) * sign if -2 **31 <= x_out <= 2 ** 31 - 1: return x_out else: return 0
相关文章推荐
- LeetCode每日一题——T8. 字符串转换整数 (atoi) (中等):正则表达式
- Leetcode每日一道 -- 整数反转
- LeetCode每日一题 005 反转字符串
- LeetCode-探索-初级-字符串-整数反转-java
- LeetCode每日一题 006 反转字符串中的单词III
- (LeetCode每日一刷02)反转整数
- 【leetcode每日一题】【2019-04-30】8. 字符串转换整数 (atoi)
- leetcode 7 使用字符串操作反转整数
- golang_算法: leetcode_字符串02-整数反转
- 【leetcode每日一题】【2019-04-28】7. 整数反转
- leetcode-字符串转整数(atoi)
- LeetCode[7] 整数反转
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- leetcode刷题之 8.字符串转换整数(atoi)
- LeetCode-第五期:344. 反转字符串-20190303
- 字符串反转成整数
- LeetCode——344. Reverse String(字符串反转)
- leetcode:String to Integer (atoi) 字符串转化成整数
- leetCode--字符串转换整数 (atoi)
- Leedcode(初级算法-字符串2):整数反转