leetcode-07-reverse integer-python

Reverse digits of an integer.
反转一个数,注意符号,溢出范围。题目说的是32位int。
自己的思路:转换成list,先拿出符号,然后不断pop掉的字符加在一起最后如果没溢出就输出。感觉很妙,像堆栈的感觉。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        y=list(str(x))
        z=""
        if '-' in y:
            z+='-'
            y.remove('-')
        for i in range(len(y)):
            z+=y.pop()
        return int(z) if abs(int(z))<=math.pow(2, 31) else 0

测试通过,很慢。效率低。
看到有一个简洁的。

class Solution:  
    # @return an integer  
    def reverse(self, x):  
        revx = int(str(abs(x))[::-1])  
        if revx > math.pow(2, 31):  
            return 0  
        else:  
            return revx * cmp(x, 0)  

思路差不多,就是用了字符串[::-1]这个直接反转字符串。

a="hello"
b=a[::-1]
print(b)

结果:

olleh
Press any key to continue . . .

测试时间比我自己的代码还要长。。72ms vs 84ms。所以内置的一些功能简单方便但是不一定快。
还有一点就是范围溢出问题了。math.pow(a,b)返回a的b次幂。

unsigned int: 4294967295(2^32-1)
signed int: 2^31-1

有符号数所以是31次幂。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值