1.题目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
2.解析:
题目的意思是实现整数的逆序,在Python中实现逆序用切片是一种便捷方式,但是切片可以使用的对象是列表,元祖,字符串,并不包括整数,这时可以考虑把整数转换成字符串,然后再把字符串转换成整数;
3.代码:
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ flag = 1 if x >= 0 else -1 new_x, x = 0, abs(x) while x: new_x = 10 * new_x + x % 10 x /= 10 new_x = flag * new_x return new_x if new_x < 2147483648 and new_x >= -2147483648 else 0
4.相关参考:
切片的相关知识>
http://blog.sina.com.cn/s/blog_7e4ac8b501014jki.html
http://blog.csdn.net/syylx/article/details/44902045