comparing dynamic int value to reverse of its value, not comparing properly. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

comparing dynamic int value to reverse of its value, not comparing properly.

import java.util.Scanner; @SuppressWarnings("all") public class Palindrome { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter any number to check if its palindrome or not :"); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int rev = 0,temp; //temp = num; while(num != 0) { rev = rev * 10; rev = rev + num%10; num = num / 10; } System.out.println(rev); if(rev == num) { System.out.println("Its a palindrome number"); }else { System.out.println("Its not a palindrome number"); } } } when comparing 2 int values whether they are same or not, in this palindrome program, the control is going to the "ELSE" part, but if I assign the "num" value to "temp" and in IF clause if i give -> if(rev == temp), then its working properly. Why is it happening like this??

7th Jan 2023, 2:48 PM
Harshanand Raykar
Harshanand Raykar - avatar
2 Answers
+ 1
Because by the time the while...loop completed, <num> will be zero. If you save a copy of <num> value into <temp>, and you compare <rev> against <temp> (instead of <num>) after the while...loop, then it really doesn't matter even though <num> became zero after the while...loop The point is, we gotta have a copy of the original number to be compared against the reversed version of it.
7th Jan 2023, 4:36 PM
Ipang
+ 1
Gotcha, thank you✨
7th Jan 2023, 4:42 PM
Harshanand Raykar
Harshanand Raykar - avatar