Definition: A palindrome number is a number that reads the same forward and backward. To determine whether a given number is a palindrome or not, you can follow these steps:
1. Accept the input number from the user.
2. Convert the number to a string.
3. Compare the characters from the beginning and the end of the string, moving inwards until they meet.
4. If all characters match, the number is a palindrome. Otherwise, it's not.
Here's the Java program to achieve this:
import java.util.Scanner; public class PalindromeNumber { public static void main(String[] args) { // Step 1: Accept input from the user Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.close(); // Step 2: Convert the number to a string String numStr = Integer.toString(number); // Step 3: Compare characters boolean isPalindrome = true; int left = 0; int right = numStr.length() - 1; while (left < right) { if (numStr.charAt(left) != numStr.charAt(right)) { isPalindrome = false; break; } left++; right--; } // Step 4: Display the result if (isPalindrome) { System.out.println(number + " is a palindrome."); } else { System.out.println(number + " is not a palindrome."); } } } (code-box)
Explanation:
1. We use the `Scanner` class to accept input from the user.
2. The input number is converted to a string using `Integer.toString()`.
3. We use two pointers (`left` and `right`) to compare characters from the beginning and the end of the string.
4. If at any point the characters at the corresponding positions don't match, we set the `isPalindrome` flag to `false` and break out of the loop.
5. After the loop, we check the value of the `isPalindrome` flag to determine whether the number is a palindrome or not and display the appropriate message.
Now you have a Java program that can determine whether a given number is a palindrome or not. Just compile and run the program, and provide the input number to see the result.
🚀 Elevate Your Career with Studyecart! 📚📊
🔥 Get instant job notifications and ace interviews with Studyecart. 📌
#StudyecartApp #CareerBoost