LeetCode 9.Palindrome Number 回文数算法

来源:互联网 发布:冰毒淘宝地址 编辑:程序博客网 时间:2024/05/20 06:27

这一个题目是判断回文数
题目要求:

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

click to show spoilers.

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.

两个方法进行处理;
(1).第一次想到的方法,好像但是方法的效率不高.
代码>>

public class solution {    public boolean isPalindrome(int x) {        System.out.println(Integer.MAX_VALUE);        if(x < 0) x = -x;        if(x < 10 && x > 0) return true;        List<Integer> list = new ArrayList<Integer>();        while(x > 0) {            list.add(x % 10);            x /= 10;        }        for(int i = 0; i < list.size() / 2;) {            if(list.get(i) == list.get(list.size() - 1 - i)) i++;            else return false;        }        return true;    }}

(2).这个方法是在讨论区看到的.效率好一些

public class fix {    public boolean isPalindrome(int x) {        //首先进行固定的个数据判断        if(x < 0) return false;        if(x < 10 && x >= 0) return true;        if(x % 10 == 0) return false;        int start = x / 10;        int end = x % 10;        while(start > end) {            end = end * 10 + start % 10;            start /= 10;        }        if(end > start) end /= 10;        return end == start ? true : false;    }}
0 0
原创粉丝点击