LeetCode Reverse Integer
2015-12-15 16:53
288 查看
LeetCode解题之Reverse Integer
原题
翻转一个intger类型的数字。注意点:
有正负两种情况
integer是32位整型,考虑溢出
注意末尾有0的情况不能直接当作字符串翻转
例子:
输入: x=123
输出: 321
输入: x=-123
输出: -321
解题思路
由于Python可以支持几乎无限大的数,直接把末尾的数不断添加到目标书中即可。最后再处理溢出的情况。如果想通过转换为字符然后翻转的方法来实现,需要把末尾的0先去掉。AC源码
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ # Consider positive and negative situation flag = 0 if x < 0: flag = -1 else: flag = 1 x *= flag result = 0 while x: result = result * 10 + x % 10 x /= 10 if result > 2147483647: return 0 else: return result * flag if __name__ == "__main__": assert Solution().reverse(321000) == 123 assert Solution().reverse(-321) == -123 assert Solution().reverse(1534236469) == 0
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析