Determine whether an integer is a palindrome. Do this without extra space.

Solution: 依次得到头尾,比较

    public boolean isPalindrome(int x) {
        if(x < 0){
            return false;
        }
        if(x < 10){
            return true;
        }
        int tens = 10;
        while(x / tens / 10 != 0){
            tens *= 10;
        }
        int anotherTens = 10;
        while(tens >= anotherTens){
            int tail = (x % anotherTens) / (anotherTens / 10);
            int head = (x / tens) % 10;
            if(head != tail){
                return false;
            }
            tens /= 10;
            anotherTens *= 10;
        }
        return true;
    }

a better way:

public boolean isPalindrome(int x) {
    if (x<0 || (x!=0 && x%10==0)) return false;
    int rev = 0;
    while (x>rev){
        rev = rev*10 + x%10;
        x = x/10;
    }
    return (x==rev || x==rev/10);
}

results matching ""

    No results matching ""