leetcode的python实现 刷题笔记7: 反转整数
2018-09-22 11:36
387 查看
给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
[code]输入: 123 输出: 321
示例 2:
[code]输入: -123 输出: -321
示例 3:
[code]输入: 120 输出: 21
注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
[code]class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ # 判断是否为个位数,是个位数则不用反转,直接返回 if -10 < x < 10: return x # 把整数x转为字符串 string = str(x) # 判断第一个是否为负号 if string[0] != "-": # 不是负号则直接反转 string = string[::-1] # str转为int x = int(string) else: # 是负号,则反转负号之后的字符串 string = string[1:][::-1] # str转int x = int(string) # 加上负号 x = -x # 判断是否溢出 # 如果-2147483648 < x < 2147483647则返回x,否则返回0 return x if -2147483648 < x < 2147483647 else 0 # 总结反思 ''' 1.访问子字符串,可以使用方括号来截取字符串,例如string[0]取的是字符串第一个元素 2.[ : ] 截取字符串中的一部分,string[::-1]表示从尾到头翻转,步长为-1 3.int类型中如果首元素是0,则忽略 '''具体字符串复习:python学习笔记:string模块,字符串的常用方法以及字符串常量示例[/code] 阅读更多
相关文章推荐
- leetcode的python实现 刷题笔记13: 罗马数字转整数
- leetcode的python实现 刷题笔记26:删除排序数组中的重复项
- leetcode的python实现 刷题笔记53:最大子序和(多种解法)
- LeetCode--Reverse Integer(整数反转)Python
- leetcode的python实现 刷题笔记70:爬楼梯(动态规划)
- leetcode的python实现 刷题笔记58:最后一个单词的长度(取巧的做法和全网最正确的做法)
- leetcode的python实现 刷题笔记27:移除元素
- 【leetcode】Reverse Integer整数反转----Java代码实现
- leetcode的python实现 刷题笔记28:实现strStr()
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- leetcode的python实现 刷题笔记14:最长公共前缀
- leetcode的python实现 刷题笔记74:搜索二维矩阵(二分查找的思想)
- leetcode的python实现 刷题笔记35:搜索插入位置的暴力解法和优化解法
- leetcode的python实现 刷题笔记9:回文数 暴力解法和进阶算法
- Python笔记——几种数据结构的实现:栈、队列及二叉树
- ip 与 整数间 的相互转换 python实现
- 《 Head First 》学习笔记:策略模式 (python实现)