我的LeetCode上的反向整数代码不被接受。你知道吗
我已经检查了我的程序是否能返回正确答案。你知道吗
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
elif (check_num[len(check_num)-1] == '0'):
check_num = check_num[:len(check_num)-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)
return oneLinerString
def main():
import sys
import io
def readlines():
for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
yield line.strip('\n')
lines = readlines()
while True:
try:
line = next(lines)
x = int(line);
ret = Solution().reverse(x)
out = str(ret);
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()
对于一个输入情况,我的程序返回正确的输出。你知道吗
Your input
123
Output
321
Expected
321
但是有错误,我的代码不被接受。 有什么问题?我应该如何修复当前的代码?你知道吗
Finished in N/A
ValueError: invalid literal for int() with base 10: ''
Line 30 in reverse (Solution.py)
Line 47 in main (Solution.py)
Line 55 in <module> (Solution.py)
尝试使用python发挥其优势:
对于0的输入,您的代码会将输入转换为空字符串,原因是:
您应该删除此elif分支,并让您的最终整数转换处理倒数的前导零:
您还需要注意当反向数超出32位有符号整数表示的范围时返回0的条件。因此,可以添加最终检查:
对示例代码进行最小的更改,一个可行的解决方案是:
相关问题 更多 >
编程相关推荐