Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> 9. Palindrome Number
Site icon onlinestudy.guru

Given an integer x, return true if x is a palindrome, and false otherwise

Palindrome Number

Palindrome Number

Palindrome Number

Example 1:

Input: x = 121

Output: true

Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121

Output: false

Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10

Output: false

Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

public class Solution {
    public boolean isPalindrome(int x) {
        // Convert integer to string
        String s = Integer.toString(x);
        
        // Use two pointers to check if the string is a palindrome
        int left = 0, right = s.length() - 1;
        while (left < right) {
            // If characters at current positions don't match, it's not a palindrome
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            // Move the pointers towards the center
            left++;
            right--;
        }
        // If the loop completes without returning false, the number is a palindrome
        return true;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int x = -121;
        boolean result = solution.isPalindrome(x);
        System.out.println("Output: " + result);
    }
}

Explanation:-

  1. isPalindrome Method:
  1. Looping through the String:
  1. Returning the Result:
  1. Main Method:

This code effectively checks whether the given integer is a palindrome by converting it to a string and comparing characters from both ends towards the center.

Exit mobile version