Search code examples
javapalindrome

I was trying to solve a Leetcode problem, regarding identifying if the number entered is a palindrome or not


I understood the logic behind the problem's solution, but in the coded solution I am a bit confused about the return statement in the end. Please explain to me what is its significance, why is it being used, etc ? (not why return is used but why is that value being returned).

class Solution {
public boolean isPalindrome(int x) {
    // 2 cases  x < 0 = false case 
    //  x > 0 = test case
    
    if (x < 0 || x % 10 == 0 && x != 0){
        return false;
    }
    else {
        int newNum = 0;
        while (x > newNum){
        int r = (x % 10);
        newNum = newNum * 10 + r;
        x /= 10;
        }
    //the part I am confused about - below     
    return x == newNum || x == newNum / 10;
    }
   
    }  
}

Solution

  • So to understand the Logic for the return statement let us take 2 numbers

    1. 1234321
    2. 678876

    So one thing here While loop is doing is to create a new number(newNum) out of X and making sure that newNum stores the reverse of X till the middle point.

    So in case of 1234321 , this while loop will execute till X=123 and newNum=1234.

    After exiting out from while loop with these values, out of the 2 statements in return, x == newNum / 10 will give true result hence return statement will return true.which means the number is palindrome.

    Please note here that the no. digits in given integer is odd(7)

    Let us now Take other example 678876

    In this case when the while loop ends, the value for the X would be 678 and newNum would be 678

    out of the 2 statements in return, x == newNum this time will give true result hence return statement will return true again .which means the number is palindrome.

    Please note here that the no. digits in given integer is even(6)

    All in all, this statement return x == newNum || x == newNum / 10; is to make sure that we are covering the condition for both Odd and even no. of digits in the given integer X.