Leetcode - Palindrome Number

Question:

Paste_Image.png

My code:

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;
        String s = Integer.toString(x);
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            if (s.charAt(i++) != s.charAt(j--))
                return false;
        }
        return true;
    }
}

My test result:

Paste_Image.png

这次作业也挺无聊的。。。然后一分钟写出来了,发现不能用额外space。其实这个要求是没意义的。什么叫extra space呢?那我不new新对象就行了吗?
应该是的,就是不在栈里面申请内存,也就是不new对象,只能申请 field。

看了下网上的做法,比较巧。直接放在这里,不想深究,觉得没有什么意义。

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;
        int m = x;
        long n = x % 10;
        while (m / 10 != 0) {
            m = m / 10;
            n = n * 10 + m % 10;
        }
        
        if (x == n)
            return true;
        else
            return false;
    }
}

**
总结:没什么好总结的。蠢比题目,我操你妈。。。
不好意思,爆粗口了。只不过做着真没意义。
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        int temp = x;
        long reverse = 0;
        while (x != 0) {
            int digit = x % 10;
            reverse = 10 * reverse + digit;
            x = x / 10;
        }
        
        return reverse == temp;
    }
}

题目比较简单,自己写的方法。然后看了答案,发现还能优化。
如果对称,那么当 x < reverse 的时候,
x只有两种可能
x == reverse (偶数位)
x == reverse / 10 (奇数位)

但是有些特别的例子需要考虑。

x = 10 ---> x = 0, reverse = 1
x = 100
x = 1000
...
满足 x == reverse / 10, 但其实他不是奇数位。
我们可以在while loop上加一些判断,但浪费时间。
所以可以直接在一开始就把这个例子给排除了。

My code:

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) {
            return false;
        }
        int reverse = 0;
        while (x > reverse) {
            reverse = 10 * reverse + x % 10;
            x = x / 10;
        }
        
        return x == reverse || x == reverse / 10;
    }
}

reference:
https://discuss.leetcode.com/topic/8090/9-line-accepted-java-code-without-the-need-of-handling-overflow

Anyway, Good luck, Richardo! -- 09/09/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容