DEV Community

Cover image for LeetCode's Palindrome Number Solution - Java
Piyush Acharya
Piyush Acharya

Posted on • Edited on

1

LeetCode's Palindrome Number Solution - Java

9. Palindrome Number

Intuition

I began by mentally walking through the given test cases and recording the steps I took to solve the problems. I used this to create some pseudocode that modeled my thinking. Following that, I translated my pseudocode into Java. I was confident that my program worked after some thorough testing in addition to the auto tests.

Approach

To allow for string indexing and length, I first converted the int to a string. Then I looped through the string until I reached the halfway point, comparing the numbers on the left and right sides. If they weren't the same, I exited the program immediately by returning false. At the end of the program, if the numbers on the left and right sides were the same, I returned true, indicating that the number entered by the user is a palindrome.

Complexity

  • Time complexity: O(n)

Code

GitHub: https://github.com/Verisimilitude11/LeetCode-Problems/tree/main/9.%20Palindrome%20Number

class Solution {
    public static boolean isPalindrome(int x) {
        String num = Integer.toString(x);
        for (int i = 0; i < num.length() / 2; i++) {
            char rightChar = num.charAt(num.length() - i - 1);
            char leftChar = (num.charAt(i));
            if (!(leftChar == rightChar)) {
                return false;
            }
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Follow me on Medium: https://medium.com/@VerisimilitudeX/leetcodes-palindrome-number-solution-java-13466d472c8e

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.