Palindrome Number

Problem

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

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.

Constraints:

  • -231 <= x <= 231 - 1

Follow up: Could you solve it without converting the integer to a string?

Solution

Reversing

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }

        var copy = x;
        var rev = 0;

        while (copy > 0) {
            rev = (rev * 10) + copy % 10;
            copy = copy / 10;
        }

        while (x > 0 || rev > 0) {
            if (x % 10 != rev % 10) {
                return false;
            }
            x = x / 10;
            rev = rev / 10;
        }

        return x == 0 && rev == 0;
    }
}

Using a Deque

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }

        var dq = new LinkedList<Integer>();
        while (x > 0) {
            dq.addLast(x % 10);
            x = x / 10;
        }

        while (dq.size() > 1) {
            if (dq.pollFirst() != dq.pollLast()) {
                return false;
            }
        }

        return true;
    }
}

Recent posts from blogs that I like

Doing nothing at work

Many engineers should be doing less work. I don’t necessarily mean producing less code or fewer changes, but literally working fewer hours in the day. When they do work, they should be working at a slower pace. I like to aim to be running at 80% utilization by default: unless I have a high-pressure ...

via Sean Goedecke

Elihu Vedder’s symbolism and stories: 1885-1913

More myth and Symbolism, with the Pleiades, Fates, and Fortuna, followed by large murals and a mosaic in the Library of Congress.

via The Eclectic Light Company

Thoughts on starting new projects with LLM agents

A few months ago I wrote about using LLM agents to help restructuring one of my Python projects. It's worth beginning by saying that the rewrite has been successful by all reasonable measures; I've been able to continue maintaining that project since then without an issue. In this post, I want to di...

via Eli Bendersky