English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to check if a number is a palindrome in Java. This is done by using for and while loops.
public class Palindrome { public static void main(String[] args) { int num = 121, reversedInteger = 0, remainder, originalInteger; originalInteger = num; //The reversed integer is stored in a variable while(num != 0) { remainder = num % 10; reversedInteger = reversedInteger * 10 + remainder; num /= 10; } //If originalInteger and reversedInteger are equal, then it is a palindrome if (originalInteger == reversedInteger) System.out.println(originalInteger + " is a palindrome."); else System.out.println(originalInteger + " is not a palindrome."); } }
When running the program, the output is:
121 is a palindrome.
In this program
First, the value of the given number (num) is stored in another integeroriginalIntegerIn the variable. This is because, we need to compare the value of the reversed number and the original number at the end.
Then, use a while loop to traverse num until it equals 0.
In each iteration, the last digit of num is stored in remainder.
Then, add the remainder to reversedInteger to add it to the next position value (multiply by10)
Then, divide by10Then, remove the last digit from num.
Finally, compare reversedInteger and originalInteger. If they are equal, then it is a palindrome number. If not, then it is not.
Here are the steps to be executed:
num | num != 0 | remainder | reversedInteger |
---|---|---|---|
121 | true | 1 | 0 * 10 +1 = 1 |
12 | true | 2 | 1 * 10 + 2 = 12 |
1 | true | 1 | 12 * 10 +1 = 121 |
0 | false | - | 121 |
public class Palindrome { public static void main(String[] args) { int num = 11221, reversedInteger = 0, remainder, originalInteger; originalInteger = num; //The reversed integer is stored in the variable for( ;num != 0; num /= 10 ) { remainder = num % 10; reversedInteger = reversedInteger * 10 + remainder; } //Palindrome, if the original integer and the reversed integer are equal if (originalInteger == reversedInteger) System.out.println(originalInteger + "is a palindrome."); else System.out.println(originalInteger + "is not a palindrome."); } }
When running the program, the output is:
11221 is not a palindrome.
In the above program, replace the while loop with a for loop.
In each iteration, num /= 10All will execute and check the condition num != 0.