-1
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.

2 Answers2

1

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.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
  • Well this might not work. For example one might input `010` and if reversed seems to be a palindrome but in the integer world, that is not a palindrome – Onyambu Apr 22 '22 at 20:58
  • @KU99, you are right, it should be solved by adding x = str(int(x)). – FLAK-ZOSO Apr 23 '22 at 04:56
1

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")