Leetcode 9. Palindrome number

stuff about computer science and programming
Post Reply
User avatar
Site Admin
Posts: 234
Joined: Wed Oct 10, 2018 3:48 am

Leetcode 9. Palindrome number

Post by dendiz » Tue Jan 29, 2019 7:31 am

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Code: Select all

Input: 121
Output: true

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

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
solving this by converting the input to a string and checking for a palindrome would defeat the purpose of the question, so I'm doing it with arithmetic.
The idea is to get the last digit of the input and make this the first digit of a temp variable that I will use to compare against. Doing this for half of the digits will yield the result. E.g:

Input: 1221

halved: 12 | 21

get the last digit with input % 10 -> 1
make it the first digit of temp: temp = temp * 10 + last digit.
integer divide input by 10 to get to the next digit.

Do this for half of the digits. But how do you know when you've reached half? Each iteration the input decreases x10 and the temp increases 10x so
when temp > input it's done. E.g:

Code: Select all

- Input: 12321  temp: 0
- Input: 1232    temp: 1
- Input: 123      temp: 12
- input: 12        temp:123
After the temp number is constructed it could have an extra digit at the due to the input having an odd number of digits. To handle that case just get rid of the last digit by dividing it by 10.

Code: Select all

    public boolean isPalindrome(int x) {
        if (x < 0) return false;
        if (x % 10 == 0 && x != 0) return false;
        int temp = 0;
        while(temp < x) {
            int r = x % 10;
            temp = temp * 10 + r;
            x = x/10;
        // even number of digits e.g 1221
        if (x == temp) return true;
        // odd number of digits e.g 121. temp will be 12 and x will 1, so temp/10 get rid
        // of last digit.
        if (temp/10 == x) return true;
        return false;

Post Reply