Home page

Monday, July 24, 2023

Check given number is palindrome or not in JAVA

A palindrome is a sequence of characters (such as a word, phrase, number, or any other sequence) that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. For example, "radar," "level," and "12321" are all palindromes.

To check whether a given string is a palindrome, you need to compare its characters from both ends inward and ensure that they match.

Here's the Java code to check if a given string is a palindrome:

public class PalindromeCheck {

    public static void main(String[] args) {

        String input = "radar"; // Change this string to test different cases

        boolean isPalindrome = checkPalindrome(input);

        if (isPalindrome) {

            System.out.println("'" + input + "' is a palindrome.");

        } else {

            System.out.println("'" + input + "' is not a palindrome.");

        }

    }

    public static boolean checkPalindrome(String str) {

        str = str.toLowerCase(); // Convert to lowercase for case-insensitive comparison

        int left = 0;

        int right = str.length() - 1;

        while (left < right) {

            char leftChar = str.charAt(left);

            char rightChar = str.charAt(right);

            if (leftChar != rightChar) {

                return false;

            }

            left++;

            right--;

        }

        return true;

    }

}

In this code, the checkPalindrome method takes a string str as input and returns a boolean value indicating whether it is a palindrome or not. We use two pointers, left and right, initialized to the start and end of the string, respectively.

The while loop runs until left is less than right. In each iteration, we compare the characters at positions left and right. If they don't match, the string is not a palindrome, and we return false. Otherwise, we increment left and decrement right to continue comparing the characters inward.

We also convert the input string to lowercase using toLowerCase() to ensure case-insensitive comparison.

The main method calls the checkPalindrome method with a sample string ("radar" in this case) and prints whether the string is a palindrome or not. You can change the input variable to test different cases.

No comments:

Post a Comment