【问题标题】:Reverse Integer on LeetCode [duplicate]LeetCode 上的反向整数
【发布时间】:2020-01-14 09:57:10
【问题描述】:

我已经编写了我的答案代码并尝试在 LeetCode 游乐场https://leetcode.com/playground/ 上运行它。

在部分

        print(check_num)
        print(check_num[len(check_num)-1])

发现程序可以接收输入及其最后一个字符。

class Solution:
    def reverse(self, x: int) -> int:
        check_num = str(x)
        flag = 0
        if(check_num[0] == '-'):
            check_num = check_num[1:]
            flag = 0

        print(check_num)
        print(check_num[len(check_num)-1])

        else if (check_num[len(check_num)-1] == '0'):
            check_num = check_num[:len(check_num)-1]

        #reverse
        storage = ['a'] * len(check_num) - 1
        for i in range(len(check_num)):
            num = -i
            storage[i] = check_num[num]

        if(flag == 1):
            storage.insert(0, '-')

        #turn to string
        oneLinerString=""
        for x in storage:
            oneLinerString += x

        return int(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()

我应该如何修复我当前的代码?

Finished in N/A
Line 12: SyntaxError: invalid syntax

【问题讨论】:

  • else if 不是有效的 Python 语法。你的意思是elif?还要记住,elif 块只能出现在 ifelif 块之后,所以你现在的缩进不起作用。

标签: python python-3.x


【解决方案1】:

如您所见,第 12 行存在语法错误。else if 在 Python 中不是有效的语法。将其更改为elif

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2022-01-13
    • 2021-12-03
    • 2018-10-25
    • 2021-09-05
    相关资源
    最近更新 更多