Sunday, February 9, 2014

Palindrome Number

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

Solution:
Basic implementation question.

public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int count = 0;
        int temp = x;
        while(temp != 0){
            count++;
            temp = temp / 10;
        }
        if(count == 0 || count == 1) return true;
        temp = x;
        int left = 0;
        int right = 0;
        for(int i = 0; i < count / 2; i++){
            right = (int)(x / Math.pow(10, i)) % 10;
            left = (int)(x / Math.pow(10, count - 1 - i)) % 10;
            if(left != right) return false;
        }
        return true;
    }
}

No comments:

Post a Comment