Thursday, January 16, 2014

Leetcode: Palindrome Number

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

Solution:

The algorithm is easy, we first obtain the number of digits and then we "traverse the number" obtaining the i first digit and i last digit.

public class Solution {
    public boolean isPalindrome(int x) {
        if(x<0)
            return false;
        if(x==0)
            return true;
int ndigits = (int)Math.log10(x)+1; for(int i=0; i<ndigits/2; i++) { int digitBegin = (x/(int)Math.pow(10,(ndigits-i-1))) % 10; int digitEnd = (x/(int)Math.pow(10,i)) % 10; if (digitBegin != digitEnd) return false; } return true; } }

No comments :

Post a Comment