check if a number is a palindrome in Java
Understanding Palindrome Numbers: A palindrome number reads the same backward as forward. For example, 121 and 1331 are palindromes.
Steps to Check for Palindrome Numbers:
12321
12321 is a palindrome.
public class PalindromeChecker {
public static boolean isPalindrome(int number) {
// Convert number to string
String original = String.valueOf(number);
// Reverse the string
String reversed = new StringBuilder(original).reverse().toString();
// Check if original and reversed strings are equal
return original.equals(reversed);
}
public static void main(String[] args) {
int number = 12321; // Example number to check
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
}
12321 is a palindrome.
isPalindrome(int number) method checks if number is a palindrome.number to a string using String.valueOf(number).StringBuilder to reverse the string representation of number.original) with the reversed string (reversed) using the equals method.import java.util.Scanner; public class PalindromeExample { public static void main(String[] args) { int n, r, sum = 0, temp; Scanner scanner = new Scanner(System.in); System.out.print("Enter the Number: "); n = scanner.nextInt(); // Read the input number temp = n; // Store the original number // Reverse the number while (n > 0) { r = n % 10; // Get the last digit sum = (sum * 10) + r; // Build the reversed number n = n / 10; // Remove the last digit } // Check if the original number and the reversed number are the same if (temp == sum) { System.out.println("Number is Palindrome."); } else { System.out.println("Number is not Palindrome."); } scanner.close(); // Close the scanner } }
n: The input number.r: The remainder when dividing by 10 (the last digit).sum: The reversed number.temp: A temporary variable to store the original number for comparison.while loop, extract the last digit of n using n % 10 and append it to sum.n by removing the last digit (n = n / 10).temp) with the reversed number (sum).First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.