Java Coding Challenge: Part 18 – Check if a Number is a Palindrome
Java Coding Challenge: Part 18 – Check if a Number is a Palindrome
Challenge:
Write a Java program to check whether a number is a palindrome or not.
A number is a palindrome if it reads the same backward as forward.
Example:
Input: 121 → Output: true
Input: 123 → Output: false
Approach:
1. Take the original number.
2. Reverse the number using a loop.
3. Compare the reversed number with the original.
Java Code:
public class PalindromeNumber {
public static void main(String[] args) {
int number = 121;
boolean isPalindrome = isPalindrome(number);
System.out.println("Is " + number + " a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(int num) {
int original = num;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return original == reversed;
}
}
This same logic can be applied to check if a string is a palindrome (with slight modifications).
0 Response to "Java Coding Challenge: Part 18 – Check if a Number is a Palindrome"
Post a Comment