Solution by vinnyoodles


  • 0
    V

    Approach #1 Reverse the number [Accepted]

    Intuition

    Similar to StringBuilder#reverse, reverse the number and check if the reversed number is equivalent to the original number.

    Algorithm

    The algorithm reverses the number by looking at the ones of the number. For every digit seen, it will be added to a variable. Each iteration must divide the number by 10 which moves a new digit into the ones digit. Also, each iteration must multiply the reversed number by 10 which moves the newly added digit into the next digit holder.

    The number is a valid palindrome if the reverse number is equivalent with the original.

    Note: all negative numbers are not palindromes because the negative sign only appears in the front.

    Java

    public boolean isPalindrome(int x) {
      int reverse = 0;
      int clone = x;
      if (x < 0) return false;
      while (clone > 0) {
        reverse = (10 * reverse) + (clone % 10);
        clone /= 10;
      }
    
      return reverse == x;
    }
    

    Complexity Analysis

    • Time complexity: $$O(n)$$. n is the number of digits in the number. Each digit is visited once.

    • Space complexity: $$O(1)$$. Only integer variables are required which are constant space and the algorithm requires two variables.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.