7. Reverse Integer

7Reverse Integer

题目描述

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.

分析

判断正负号:s=cmp(x,0)  #python2.7里,x>0返回1, x<0返回-1

倒序输出:for value in rang(10)[::-1]涉及的数字倒序输出;
    b = a[i:j:s]这种格式呢,i,j与上面的一样,但s表示步进,缺省为1,所以a[i:j:1]相当于a[i:j];
    当s>0时,i缺省时,默认为0. j缺省时,默认为len(a);(第len(a)个元素不存在,输出索引值为0~len(a)-1的数);
    当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1;

    所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍。

完整代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        s=cmp(x,0)  #python2.7里,x>0返回1, x<0返回-1
        r=int(str(abs(x))[::-1])
        return s*r*(r<2**31) #if x.bit_length()<32 else 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值