Leetcode - Palindrome Number

来源:互联网 发布:淘宝c店运营提成 编辑:程序博客网 时间:2024/06/05 04:27

Question

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


Some hints:

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

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?

There is a more generic way of solving this problem.


Java Code

public static boolean isPalindrome(int x) {    if(x<0)        return false;    else if(x > 9) {                //版本1: 通过取整取余获取每个数位上的数字,逐个比较之        int n = (int)Math.log10(x) + 1;        for(int i = 1; i <= n/2; ++i) {            if((x / (int)Math.pow(10, i - 1)) % 10 != (x / (int)Math.pow(10, n - i)) % 10)                return false;        }        //版本2: 从个位开始逐位取出每个数字,构造对应的回文数字,再整体比较是否相等(不必提前计算整数的长度)        long temp = x;        long p = 0;        while(temp != 0) {            p = p * 10 + temp % 10;            temp /= 10;        }        return (p == x);        //版本3: 利用字符串反转函数        if (Long.parseLong(new StringBuffer(String.valueOf(x)).reverse().toString()) != x)            return false;        //版本4: 构造整数对应的字符串,逐位比较对应的字符        String s = String.valueOf(x);        int n = s.length();        for(int i = 0; i <= n/2; ++i) {            if(s.charAt(i) != s.charAt(n - i - 1))                return false;        }    }    return true;}

说明

  • 这题给出了限制条件,不允许使用额外的空间,所以严格来说上述代码都是不符合要求的? 这4个版本除了版本2速度快一些(40%),其他的runtime都差不多,只能排到7%左右……不知道最优解是怎么处理的呢?
0 0
原创粉丝点击