The standard solution, compare last and first, constant space


  • 0
    M
    public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int digits = getDigits(x);
        int power = (int) Math.pow(10, digits - 1);
        int left;
        int right;
        while(x > 0) {
            left = x / power;
            right = x % 10;
            if(left != right) return false;
            x %= power;
            x /= 10;
            power /= 10;
            power /= 10;
        }
        return true;
    }
    
    private int getDigits(int x) {
        int count = 0;
        while(x > 0) {
            count++;
            x /= 10;
        }
        return count;
    }
    }

Log in to reply
 

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