<p>对于0的输入,您的代码会将输入转换为空字符串,原因是:</p>
<pre><code>elif (check_num[len(check_num)-1] == '0'):
check_num = check_num[:len(check_num)-1]
</code></pre>
<p>您应该删除此elif分支,并让您的最终整数转换处理倒数的前导零:</p>
<pre><code>ans = int(oneLinerString) # removes leading zeros in the reversed string
</code></pre>
<p>您还需要注意当反向数超出32位有符号整数表示的范围时返回0的条件。因此,可以添加最终检查:</p>
<pre><code>if not -2**31 <= ans <= 2**31 - 1:
return 0
</code></pre>
<p>对示例代码进行最小的更改,一个可行的解决方案是:</p>
<pre><code>class Solution:
def reverse(self, x: int) -> int:
check_num = str(x)
flag = 0
if(check_num[0] == '-'):
check_num = check_num[1:]
flag = 1
#print(check_num)
#reverse
time = len(check_num)
storage = [0] * time
for i in range(len(check_num)):
num = len(check_num)-i-1
storage[i] = check_num[num]
#print(storage[i])
if(flag == 1):
storage.insert(0, '-')
#turn to string
oneLinerString=""
for x in storage:
oneLinerString += x
ans = int(oneLinerString) # removes leading zeros in the reversed string
if not -2**31 <= ans <= 2**31 - 1:
return 0
return ans
</code></pre>