整数alind植物

发布于 2025-01-23 08:32:29 字数 331 浏览 3 评论 0原文

x = int(input())
if x<0 and (x%10 == 0 and x !=0):
    print("false")
rev = 0
while x>0:
    rev = rev*10 + x%10
    x = x // 10
if rev == x:
    print("true")
else:
    print("false")
    

由于相反的数字与输入的数字相同,因此条件rev == x应返回true,但给出了相反的情况。我在做什么错?

编辑1:不允许将转换为字符串


编辑2:

x = int(input())
if x<0 and (x%10 == 0 and x !=0):
    print("false")
rev = 0
while x>0:
    rev = rev*10 + x%10
    x = x // 10
if rev == x:
    print("true")
else:
    print("false")
    

Since the reversed number is the same as entered one, the condition rev == x should return true but it's giving the opposite. What am I doing wrong?

Edit 1: converting to string is not allowed


Edit 2: ???? I see now.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌酱 2025-01-30 08:32:29

建议:

x = int(input())

您正在阅读x by input(),因此,检查它是否会逆转它是一个更好的想法:

x = input()
if (x == x[::-1]):
    ...

更好地理解[:: - 1 ]我建议您阅读 this


回答:

您的way循环修改x,因此它不再具有原始输入值。它以0

退出

的评论中的某人退出,这是您真正的问题。

while x>0:
    rev = rev*10 + x%10
    x = x // 10

更清楚地说,我建议您阅读代码的这一部分,并想知道the loop 循环结束时x的值是什么。

Suggestion:

x = int(input())

You are reading x by input(), so a better idea to check if it's palindrome would be reversing it:

x = input()
if (x == x[::-1]):
    ...

To better understand [::-1] I would suggest you to read this.


Answer:

Your while loops modifies x, so it no longer has the original input value. It exits as 0

Somebody in the comments said this, which is your real problem.

while x>0:
    rev = rev*10 + x%10
    x = x // 10

To be clearer I would suggest you to read this part of your code, and to wonder what will be the value of x at the end of the while loop.

南街九尾狐 2025-01-30 08:32:29

无论输入X等于while循环之后,您都在段循环内更新“ x”值。

在输入()之后,将X值复制到某个温度变量,并在IF条件下进行比较。

x = 121
x1=x
if x<0 and (x%10 == 0 and x !=0):
    print("false")
rev = 0
while x>0:
    rev = rev*10 + x%10
    x = x // 10
#print(x1,rev)
if rev == x1:
    print("true")
else:
    print("false")

You are updating the 'x' value inside the while loop, irrespective of the input x equals 0 after the while loop.

Copy x value to some temp variable after the input() and compare that in the if condition.

x = 121
x1=x
if x<0 and (x%10 == 0 and x !=0):
    print("false")
rev = 0
while x>0:
    rev = rev*10 + x%10
    x = x // 10
#print(x1,rev)
if rev == x1:
    print("true")
else:
    print("false")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文