[leetcode]Palindrome Number

普通题。需要注意的是反转时的溢出。还有正负符号。(居然我没有特别加正负的判断也过了... 想了一下才发现根据我的代码负数的时候都会抛Exception,歪打正着。)

public class Solution {
    public boolean isPalindrome(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        try
    	{
    		int r = reverse(x);
    		if (r == x)
    		{
    			return true;
    		}
    		else
    		{
    			return false;
    		}
    	}
    	catch (RuntimeException ex)
    	{
    		return false;
    	}
    }
    
    private int reverse(int x)
    {
    	int ans = 0;
        while( x > 0)
        {
        	int d = x - x / 10 * 10;
        	x = x / 10;
        	if (Integer.MAX_VALUE / 10 < ans
        			|| Integer.MAX_VALUE - d < ans * 10)
        	{
        		throw new RuntimeException();
        	}
        	ans = ans * 10 + d;
        }
        return ans;
    }
}

另一种做法似乎更好就是取最左边一个数和最右边的数比较,然后去掉左右边。相比我的做法更好之处是无需考虑溢出。

参见:http://www.cnblogs.com/remlostime/archive/2012/11/13/2767676.html

posted @ 2013-07-26 13:48  阿牧遥  阅读(277)  评论(1)    收藏  举报