7 | Reverse Integer | 24.40% | 反转数字,注意首位为0 |
32bit:数字大小小于2^31 |
string反转方法:[::-1] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 24 20:13:51 2017
@author: vicky
"""
#102ms
#import numpy as np;
import math
#self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。
#没有class类,只有def函数时,不用self
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s2=0
if x==0:
s2=0
else:
k=int(math.log10(abs(x)))
s=abs(x)
x2={} #提取各位数字
for i in range(k+1):
x2[i]=int(s/(10**(k-i)))
s=s-x2[i]*(10**(k-i))
for i in range(0,k+1):
s2=s2+x2[k-i]*(10**(k-i))
if x<0:
s2=-1*s2
return s2 if abs(s2)<2**31 else 0 #32-bit意思是小于数字大小小于2^32
x=-15342360
t=Solution()
t.reverse(x)
print(t.reverse(x))
#import operator
#def reverse( x):
# s = operator.lt(x, 0)
# r = int('s*x'[::-1])
# return s*r * (r < 2**31)
#
#reverse(1534236469)
#98ms
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#先把转换为str型,再转换为int型,不用考虑首位为0因为int
x = int(str(x)[::-1]) if x >= 0 else -int(str(-x)[::-1])
return x if x < 2147483648 and x >= -2147483648 else 0
#99ms
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s3=abs(x)
sign_x=1 if x>0 else -1
new_x=0
while s3>0:
new_x=10*new_x+s3%10
s3=int(s3/10)
return sign_x*new_x if new_x<2**31 else 0