9. Palindrome Number

来源:互联网 发布:java opencv图像识别 编辑:程序博客网 时间:2024/05/24 03:35

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

hint
Could negative integers be palindromes? (ie, -1) no

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

code

public class PalindromeNumber {    public boolean isPalindrome(int x) {        if (x < 0)            return false;        return x == reverse(x);    }    public int reverse(int a) {        long ret = 0;        while (a != 0) {            ret = ret * 10 + a % 10;            a /= 10;        }        if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {            ret = 0;        }        return (int) ret;    }}
0 0
原创粉丝点击