[英]Reversing an integer in python is not working
def intreverse(n): #reverses an integer
x=0
d=0
while(n>0):
d=n%10
x=x*10+d
n=n/10
return x
為什么這段代碼沒有給我 python 中整數的反轉?
如果您使用的是 Python 3,請使用整數除法//
因為/
會給您一個浮點數。
def intreverse(n):
x=0
d=0
while n > 0:
d = n % 10
x= x * 10 + d
n = n // 10
return (x)
您甚至可以通過在 while 循環之前刪除變量 d 來改進您的代碼,因為它的值在您進入循環時被重新分配,並且您還可以使用擴充賦值運算符//=
而不是n = n // 10
,因此您可以將會:
def intreverse(n):
x = 0
while n > 0:
d = n % 10
x = x * 10 + d
n //= 10
return x
如果您擔心特定整數大小的溢出,您可以使用簡單的 if 語句 [-2^(31), 2^(31) - 1] 檢查整數是否在 32 位范圍內
def intreverse(self, x: int) -> int:
negative = False
if x < 0:
negative = True
x = x * -1
res = 0
while x != 0:
res = (res * 10) + x % 10
x = x // 10
if (res > (2 ** 31) - 1) or (res < -(2 ** 31)):
return 0
return (res * -1) if negative else res
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.