0

Please, explain why num 1 = num also, why m = m *10 + num%10 and num/=10 ? See below program

import java.util.Scanner; public class Palindrome { public static void main (String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); int num1=num; int m=0; while (num>0) { m= m*10 +num%10; num/=10; } if (num1==m) { System.out.println(" the number is a palindrome"); } else System.out.println(" the number is not a palindrome"); }

9th Dec 2016, 1:59 PM
Varun Singh
Varun Singh - avatar
2 Antworten
+ 3
Briefly, this program accepts an integer from the standard input and determines if it is a palindrome (meaning it is the same number when written forwards or backwards.) Note the program is assuming a base or radix of 10. It starts by creating a scanner instance with the standard input. Then it (attempts to) get an integer from the scanner. (There is a possible exception if the user does not enter an integer value.) Next it uses a loop to reverse the order of the digits in the number. The while condition checks that there are there digits remaining in num. The first statememt in the while takes the last digit from num and makes it the next digit in m. The second statement in the while removes the last digit from num. When the while loop terminates m contains the orignal number written in reverse. If it is the same as the original value save in num1 then the number is a palindrome. (The same value when written backwards as when written forwards.) Otherwise it is not. By using the constant 10 the program assumes a decimal representation of the number instead of binary or hexadecimal or some other radix.
9th Dec 2016, 2:17 PM
Gordon Garmaise
Gordon Garmaise - avatar
+ 2
m = m * 10 + num % 10; num % 10 is the last decimal digit of num. m * 10 adds a zero to the end of m. + adding the two together adds the last digit of num to the end of m. = m is set to this new number. num /= 10; Divides n by 10. In integer arithmetic this removes the last digit from num. This becomes the new value of num. As the loop progresses the decimal digits of num are moved to m in reverse order. When all the digits of num are used up, m has the origin value of num written backwards in decimal.
9th Dec 2016, 3:12 PM
Gordon Garmaise
Gordon Garmaise - avatar